Xin Xing briefly analyzes the connection and difference between array_walk and array_map array walk class array walk trim array walk anonymous function

WBOY
Release: 2016-07-29 08:54:24
Original
1177 people have browsed it

Let’s take a look at the specific usage of these two functions. The first is array_walk, the code is as follows:

<?php
$arr = array(2,4,5,6,7);

function xin(&$val,$key){
	$val =  $val*$val;
}

array_walk($arr, "xin");
var_dump($arr);
Copy after login
The output content is as follows:

array (size=5)
  0 => int 4
  1 => int 16
  2 => int 25
  3 => int 36
  4 => int 49
Copy after login
As for array_map, let’s also give an example :

<?php

function xin($a,$b){
	return $a*$b;
}
 
$arr = array(2,3,4,5);
$brr = array(5,6,7,8);
$crr = array_map("xin",$arr,$brr);
var_dump($crr);
Copy after login
The output is as follows:

array (size=4)
  0 => int 10
  1 => int 18
  2 => int 28
  3 => int 40
Copy after login

We can find that for example, traversing an array, both functions can be implemented, but generally speaking, their focus is different:

(1)array_map can traverse n arrays at the same time, while array_walk usually traverses one.

(2)array_map must have a return value, because its return value needs to form a new array. But array_walk is usually not necessary, because its usual use is to change the original data.

(3)array_map usually has a role of data, but array_walk does not recommend deleting or adding data, only recommends modifying the value.

Of course, they can achieve the same function in some cases. The two are not distinct, but have certain intersections.

The above introduces Xin Xing's brief analysis of the connection and difference between array_walk and array_map, including the content of array and walk. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!