PHP preliminary note (6)-adding elements to an array

Source: Internet
Author: User
PHP note (6)-adding elements to an array today I learned how to add an element to a PHP array. Previously, we used the push () function to add: $ arrarray (); array_push ($ arr, el1, el2.... eln );? But there is actually a more direct and convenient way: $ arrarray (); $ arr [] el1; $ arr [] el2 ;... $ arr [] PHP note (6)-add elements to an array

Today I learned how to add an element to a PHP array.

Previously, the push () function was always used to add:

$arr = array();array_push($arr, el1, el2 ... eln);

?

But there is actually a more direct and convenient way:

$arr = array();$arr[] = el1;$arr[] = el2;...$arr[] = eln;

?

Experiments show that the efficiency of the second method is nearly twice higher than that of the first method!

Let's take a look at the following example:

$t = microtime(true); $array = array(); for($i = 0; $i < 10000; $i++) {     $array[] = $i; } print microtime(true) - $t; print '
'; $t = microtime(true); $array = array(); for($i = 0; $i < 10000; $i++) { array_push($array, $i); } print microtime(true) - $t;

Run the script and the result is:

? Write

Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array []
Run 2
0.0054559707641602 // array_push
0.002892017364502 // array []
Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array []

?

It's really amazing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.