PHP的数组函数array_map,array_walk,arr

2019-08-07  本文已影响0人  PHP的点滴

先来说下异同点

相同点:

不同点:

参数说明

array_map(function($v){
}, $array);
array_walk($array, function($v, $k){
});
array_filter($array, function($v){
});

示例演示

  1. 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)
 */
  1. 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)
*/
  1. 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 对参数数组的元素进行过滤,返回【新数组】,【不改变原数组】的值。

上一篇下一篇

猜你喜欢

热点阅读