先来说下异同点
相同点:
- 操作对象是数组
- 都是利用回调函数对数组中每个元素进行操作
不同点:
- 返回值
- 回调函数的参数
- 是否改变数组的值
参数说明
array_map(function($v){
}, $array);
array_walk($array, function($v, $k){
});
array_filter($array, function($v){
});
示例演示
- array_map 返回的是新数组,原数组不变(新数组和原数组的数组长度应该一样)
$arr = [
'i1' => 'this is i1',
'i2' => 'this is i2',
'i3' => 'this is i3',
'i4' => 'this is i4',
];
$ret = array_map(function ($v) {
if($v == 'this is i2'){
return '修改';
}
return $v;
}, $arr);
var_dump($ret);
/*
array (size=4)
'i1' => string 'this is i1' (length=10)
'i2' => string '修改' (length=6)
'i3' => string 'this is i3' (length=10)
'i4' => string 'this is i4' (length=10)
*/
- array_walk 返回的布尔值,如果要改变数组元素的值,回调函数第一个参数必须是引用
$arr = [
'i1' => 'this is i1',
'i2' => 'this is i2',
'i3' => 'this is i3',
'i4' => 'this is i4',
];
$ret1 = array_walk($arr, function(&$v, $k){
if($v == 'this is i2'){
$v = '修改 $v';
}
});
var_dump($arr);
/*
array (size=4)
'i1' => string 'this is i1' (length=10)
'i2' => string '修改 $v' (length=9)
'i3' => string 'this is i3' (length=10)
'i4' => string 'this is i4' (length=10)
*/
- array_filter 返回的是【新数组】,原数组不变。它的作用是过滤数组中的元素。回调函数返回 true,元素才能保存到新数组中
$arr = [
'i1' => 'this is i1',
'i2' => 'this is i2',
'i3' => 'this is i3',
'i4' => 'this is i4',
];
$ret2 = array_filter($arr, function($v){
if($v == 'this is i4'){
return false;
}
return true;
});
var_dump($ret2);
/*
array (size=3)
'i1' => string 'this is i1' (length=10)
'i2' => string 'this is i2' (length=9)
'i3' => string 'this is i3' (length=10)
*/
结论
array_map 对参数数组的每个元素进行操作,返回【新数组】,【不改变原数组】的值
最常见的场景就是 intval()、trim() 数组中的值
array_walk 对参数数组的每个元素进行操作,返回【布尔】,【改变原数组】的值。
array_filter 对参数数组的元素进行过滤,返回【新数组】,【不改变原数组】的值。
网友评论