用回调函数对数组中的每个元素自定义【array_walk】

<?php
$array = array(
0 => '霜天部落',
1 => false,
2 => 1,
3 => null,
4 => '',
5 => 'http://www.XXX.com',
6 => '0'
);
function myFun($value,$key){
if($key %2 == 0){
echo "The key $key has the value $value<br/>";
}
}
array_walk($array,'myFun');
print_r($array);
/*
输出:
The key 0 has the value 霜天部落
The key 2 has the value 1
The key 4 has the value
The key 6 has the value 0
Array ( [0] => 霜天部落 [1] => [2] => 1 [3] => [4] => [5] => http://www.XXX.com [6] => 0 )
*/


?>

补充:

<?php
$array = array(
0 => '霜天部落',
1 => false,
2 => 1,
3 => null,
4 => '',
5 => 'http://www.XXX.com',
6 => '0'
);
function myFun(&$value,$key){//传入引用
$value = '好的';
if($key %2 == 0){
echo "The key $key has the value $value<br/>";
}
}
array_walk($array,'myFun');
print_r($array);
/*
输出:
The key 0 has the value 好的
The key 2 has the value 好的
The key 4 has the value 好的
The key 6 has the value 好的
Array ( [0] => 好的 [1] => 好的 [2] => 好的 [3] => 好的 [4] => 好的 [5] => 好的 [6] => 好的 )
*/


?>

原文地址:https://www.cnblogs.com/lbs8/p/5722406.html