Home >Backend Development >PHP Problem >How to change associative array in php

How to change associative array in php

藏色散人
藏色散人Original
2021-11-04 10:18:472813browse

php method to change the associative array: 1. Create an intermediate temporary array, and then modify it through traversal assignment; 2. Use the callback function array_map() to modify the array; 3. Use the foreach statement to modify the array.

How to change associative array in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

php How to change the associative array?

php modify the associative array

There are the following requirements, traverse the array and make corresponding changes to the value of the array, for example, set all to 0;

It would be easier if all the arrays were index arrays, just use for() to traverse and modify them.

But if it is an associative array, it is a pain. To traverse the index array, you need to use foreach, but foreach is read-only, that is, modifications cannot be made.

There are three methods now:

1. Make an intermediate temporary array: temp = array(). Then just assign values ​​while traversing.

2. Use the callback function array_map()

Example:

$arr = array_map(function($p) {return 0;}, $arr);               //p代表了元素的值,一个一个来

This way you can set everything.

Or:

array_walk($arr, function(&$value, $key) {
     $value = 0;
});

The above two methods modify the original array and do not generate a new array

The third and simplest method:

foreach($arr as $k => &$v) {
     $v = 0;
}

Note: Do not try to change the key value, the key value cannot It is a reference to

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to change associative array 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