Home >Backend Development >PHP Tutorial >How to Push Key-Value Pairs into Associative Arrays in PHP?

How to Push Key-Value Pairs into Associative Arrays in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 10:57:091034browse

How to Push Key-Value Pairs into Associative Arrays in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn