Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How php changes associative arrays

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to change associative arrays in php". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Php changes the associative array: 1, create an intermediate temporary array, and then modify it by traversing assignments; 2, use the callback function array_map () to modify the array; 3, use the foreach statement to modify the array.

This article operating environment: Windows7 system, PHP7.1 version, DELL G3 computer

How does php change associative arrays?

Php modifies associative array

There is a need to traverse the array and change the values of the array accordingly, for example, all set to 0

It would be easy if the array were all indexed, just use for () to modify it while traversing.

But if it is an associative array, it hurts to use foreach to traverse the indexed array, but foreach is read-only, that is, no changes can be made.

Now there are three ways:

1. Make an intermediate temporary array: temp = array (). And then it goes through it and assigns a value to it.

2. Use the callback function array_map ()

Example:

$arr = array_map (function ($p) {return 0;}, $arr); / / p represents the value of the element, one by one

So you can set it all up.

Or:

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

Both of the above methods are modified in the original array and do not generate a new array.

The third and easiest way:

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

Note: do not attempt to change the key value, the key value cannot be a reference

That's all for "how php changes associative arrays". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report