Home >Backend Development >PHP Tutorial >How to Append Key-Value Pairs to PHP Arrays?
Appending Key-Value Pairs to PHP Arrays
In PHP, while the array_push() function is commonly used to add elements to an array, it cannot be directly employed for associative arrays, which contain key-value pairs.
To address this issue, the print_r function can be used to print the output of an array, as seen in the example:
$GET = array(); $key = 'one=1'; $rule = explode('=', $key); $GET[$rule[0]] = $rule[1]; // Manually assign key-value pair
This code uses the explode() function to split the key into its components, and then manually assigns the key and value to the $GET array using the syntax $arrayname[indexname] = $value.
While array_push() is not directly applicable to associative arrays, the above approach provides a simple and straightforward method to append key-value pairs to these data structures.
The above is the detailed content of How to Append Key-Value Pairs to PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!