How to push both value and key into PHP array
Nope, there is no array_push()
equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+
) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);
.
There's more info on the usage of the union operator vs array_merge
in the documentation at http://php.net/manual/en/function.array-merge.php.