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
Release: 2024-12-05 10:57:09
Original
1042 people have browsed it

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);
Copy after login

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, ...] */
Copy after login

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;
Copy after login

In our example:

$GET[$rule[0]] = $rule[1];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template