note 118963 added to function.array-push
| From: | mrgreen dot webpost at gmail dot com | Date: | Wed, 09 Mar 2016 02:11:19 +0000 |
| Subject: | note 118963 added to function.array-push | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205118@lists.php.net to get a copy of this message | ||
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you
can instead just do...
$data[$key] = $value;
...but this is actually not true. Unlike array_push and even...
$data[] = $value;
...Rodrigo's suggestion is NOT guaranteed to append the new element to the END of the array.
For instance...
$data['one'] = 1;
$data['two'] = 2;
$data['three'] = 3;
$data['four'] = 4;
...might very well result in an array that looks like this...
[ "four" => 4, "one" => 1, "three" => 3,
"two" => 2 ]
I can only assume that PHP sorts the array as elements are added to make it easier for it to find a
specified element by its key later. In many cases it won't matter if the array is not stored
internally in the same order you added the elements, but if, for instance, you execute a foreach on
the array later, the elements may not be processed in the order you need them to be.
If you want to add elements to the END of an associative array you should use the unary array union
operator (+=) instead...
$data['one'] = 1;
$data += [ "two" => 2 ];
$data += [ "three" => 3 ];
$data += [ "four" => 4 ];
You can also, of course, append more than one element at once...
$data['one'] = 1;
$data += [ "two" => 2, "three" => 3 ];
$data += [ "four" => 4 ];
Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which
means that if you are building an array in a loop you need to declare an empty array first...
$data = [];
for ( $i = 1; $i < 5; $i++ ) {
$data += [ "element$i" => $i ];
}
...which will result in an array that looks like this...
[ "element1" => 1, "element2" => 2, "element3" => 3,
"element4" => 4 ]
----
Server IP: 72.52.91.14
Probable Submitter: 99.243.51.172
----
Manual Page -- http://php.net/manual/en/function.array-push.php
Edit -- https://master.php.net/note/edit/118963
Del: integrated -- https://master.php.net/note/delete/118963/integrated
Del: useless -- https://master.php.net/note/delete/118963/useless
Del: bad code -- https://master.php.net/note/delete/118963/bad+code
Del: spam -- https://master.php.net/note/delete/118963/spam
Del: non-english -- https://master.php.net/note/delete/118963/non-english
Del: in docs -- https://master.php.net/note/delete/118963/in+docs
Del: other reasons-- https://master.php.net/note/delete/118963
Reject -- https://master.php.net/note/reject/118963
Search -- https://master.php.net/manage/user-notes.php