How to push both value and key into array


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:

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

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

7/11/2016 2:40:06 PM

Accepted Answer

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;
1/23/2010 12:45:43 AM

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;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow