How to push both value and key into PHP array

Viewed 1054186

Take a look at this code:

$GET = array();    
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */

I'm looking for something like this so that:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */

Is there a function to do this? (because array_push won't work this way)

20 Answers

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;

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

For add to first position with key and value

$newAarray = [newIndexname => newIndexValue] ;

$yourArray = $newAarray + $yourArray ;

I wrote a simple function:

function push(&$arr,$new) {
    $arr = array_merge($arr,$new);
}

so that I can "upsert" new element easily:

push($my_array, ['a'=>1,'b'=>2])
array_push($GET, $GET['one']=1);

It works for me.

There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.

$intial_content = array();

if (true) {
 $intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}

I usually do this:

$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
Related