Home >Backend Development >PHP Tutorial >How to Add Both Key and Value to a PHP Associative Array?
How to Push Both Value and Key into PHP Array
Adding elements to PHP arrays is a common task, but when dealing with associative arrays, the conventional array_push() function doesn't suffice. This article addresses the question of inserting both a key and a value into an associative array.
To achieve this, you can directly assign the value to the array using the square bracket notation:
$GET[indexname] = $value;
In the example provided, you can update the code as follows:
$GET = array(); $key = 'one=1'; $rule = explode('=', $key); $GET[$rule[0]] = $rule[1];
This will push both the key and its associated value into the $GET array. The resulting array can be printed using print_r() to display both keys and values:
print_r($GET); /* output: $GET[one => 1, two => 2, ...] */
Note that unlike array_push(), this method does not guarantee the order of keys in the resulting array.
The above is the detailed content of How to Add Both Key and Value to a PHP Associative Array?. For more information, please follow other related articles on the PHP Chinese website!