Home > Backend Development > PHP Problem > php adds key-value pairs to array

php adds key-value pairs to array

藏色散人
Release: 2023-03-06 11:36:02
Original
5529 people have browsed it

php method to add key-value pairs to an array: First create a PHP sample file; then use the foreach statement to add key-value pairs to the array, with statements such as "foreach ($a as &$item) { $item['b'] = "value";}".

php adds key-value pairs to array

Recommended: "PHP Video Tutorial"

Use foreach to add key-value pairs to the array in php

In PHP, the frequency of using foreach to traverse arrays is very high, and its performance is higher than the combination of list() and each() to traverse arrays:

When traversing the first level of a two-digit array array, and want to add a new key-value pair to the second array. For example, I have a two-dimensional array structure like this

$a = array(
     array(
        'a' => "first"
      ),
     array(
        'a' => "second"
      )
 );
Copy after login

This is my plan to add a key-value pair to each array in the second layer

 'b' => "value"
Copy after login

If foreach is used at this time

foreach ($a as $item) {
        $item['b'] = "value";
    }
Copy after login

The result obtained is the same as the original array, and the key-value pair 'b' is not added => "value"

only We need to make some modifications to the above code to achieve our needs, that is, add an address character & before $item, as follows

foreach ($a as &$item) {
        $item['b'] = "value";
    }
Copy after login

The array obtained in this way is the content we want .

The above is the detailed content of php adds key-value pairs to array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template