Voting

: min(one, four)?
(Example: nine)

The Note You're Voting On

mrgreen dot webpost at gmail dot com
9 years ago
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 ]

<< Back to user notes page

To Top