Home >Backend Development >PHP Tutorial >How Do I Add Key-Value Pairs to PHP Associative Arrays?
In PHP, arrays can hold both numerically indexed elements and key-value pairs, known as associative arrays. When dealing with associative arrays, there is a common desire to add a new key-value pair to the array, similar to array_push for numerically indexed arrays.
Unfortunately, there is no built-in function in PHP that mimics array_push for associative arrays. Instead, you will need to explicitly set the key and value using the array assignment syntax:
$GET[indexname] = $value;
Consider the following code:
$GET = array(); $key = 'one=1'; $rule = explode('=', $key); $GET[$rule[0]] = $rule[1]; // Use bracket syntax to set key
After executing this code, $GET will contain the key-value pair ['one' => '1'].
It's essential to note that if your array key contains spaces or special characters, it must be enclosed in quotes to ensure it is treated as a string. For example:
$array['my key name'] = 'John Doe';
Pushing elements into associative arrays requires the use of the array assignment syntax $array[key] = value. There is no dedicated function for this task in PHP.
The above is the detailed content of How Do I Add Key-Value Pairs to PHP Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!