Home > Backend Development > PHP Tutorial > How to Add Both Key and Value to a PHP Associative Array?

How to Add Both Key and Value to a PHP Associative Array?

Susan Sarandon
Release: 2024-12-15 04:51:17
Original
696 people have browsed it

How to Add Both Key and Value to a PHP Associative Array?

How to Push Both Value and Key into PHP Array

Adding elements to PHP arrays is a common task, but when dealing with associative arrays, the conventional array_push() function doesn't suffice. This article addresses the question of inserting both a key and a value into an associative array.

To achieve this, you can directly assign the value to the array using the square bracket notation:

$GET[indexname] = $value;
Copy after login

In the example provided, you can update the code as follows:

$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
$GET[$rule[0]] = $rule[1];
Copy after login

This will push both the key and its associated value into the $GET array. The resulting array can be printed using print_r() to display both keys and values:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Copy after login

Note that unlike array_push(), this method does not guarantee the order of keys in the resulting array.

The above is the detailed content of How to Add Both Key and Value to a PHP Associative Array?. 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