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

php adds key-value pairs to array

藏色散人
藏色散人Original
2020-10-05 00:42:015486browse

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"
      )
 );

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

 'b' => "value"

If foreach is used at this time

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

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";
    }

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!

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