Pushing Values into Associative Arrays in PHP with Array Keys
Creating associative arrays can be a useful technique in programming, and PHP provides a method to both associate values with keys and push them into arrays.
To address a specific challenge faced by developers, let's consider the following code:
$GET = array(); $key = 'one=1'; $rule = explode('=', $key);
The goal is to create an associative array where the key-value pairs are derived from the exploded values in $rule. The desired output would resemble:
print_r($GET); /* output: $GET[one => 1, two => 2, ...] */
Solution
While array_push() is commonly used to add elements to an array, it cannot be applied directly to associative arrays. Instead, we employ the following syntax:
$arrayname[indexname] = $value;
In our example:
$GET[$rule[0]] = $rule[1];
This will effectively add the key-value pair to the $GET associative array.
The above is the detailed content of How to Push Key-Value Pairs into Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!