php array_walk()函数
php array_walk()函数是php中一个非常有用的数组函数,它可以对数组中的每个元素应用用户自定义的回调函数。它可以在每个数组元素上应用用户提供的函数,而不必像array_map()函数那样返回一个新的数组。
使用方法
array_walk()函数的第一个参数是数组,第二个参数是用户定义的回调函数,第三个参数是可选参数,用于传递给回调函数的额外参数。
//定义回调函数 function myfunction($value,$key) { echo "The key $key has the value $value\n"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); //调用array_walk()函数 array_walk($a,"myfunction"); /* 输出结果: The key a has the value red The key b has the value green The key c has the value blue */
如果需要传递额外参数,则可以使用第三个参数:
function myfunction($value,$key,$p) { echo "The key $key has the value $value and the parameter $p\n"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); $p="extra"; array_walk($a,"myfunction",$p); /* 输出结果: The key a has the value red and the parameter extra The key b has the value green and the parameter extra The key c has the value blue and the parameter extra */
array_walk()函数可以用来遍历数组,并对数组中的每个元素应用用户自定义的回调函数,从而实现各种功能,如计算数组中每个元素的和,计算数组中每个元素的平均值等等。
- array_walk()函数可以对数组中的每个元素应用用户自定义的回调函数。
- array_walk()函数的第一个参数是数组,第二个参数是用户定义的回调函数,第三个参数是可选参数,用于传递给回调函数的额外参数。
- array_walk()函数可以用来遍历数组,并对数组中的每个元素应用用户自定义的回调函数,从而实现各种功能。