php的array_walk,PHP array_walk() 函数详解

定义

array_walk - 对数组的每个元素应用自定义函数

描述

array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool

回调函数的参数,第一个是元素值,第二个是元素键名,第三个是可选的 $userdata。

如果只想改变数组值,第一个参数可使用引用传递,即在参数前加上 &。

示例

$fruits = array("a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)

{

$item1 = "$prefix: $item1";

}

function test_print($item2, $key)

{

echo "$key. $item2
\n";

}

echo "Before ...:\n";

array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');

echo "... and after:\n";

array_walk($fruits, 'test_print');

?>

将输出:

Before ...:

a. orange

b. banana

c. apple

... and after:

a. fruit: orange

b. fruit: banana

c. fruit: apple

总结

上面说如果想改变数组的值,必须使用引用传递,于是我想能不能不这样,直接使用返回值,测试了一下,是不行的,因为回调函数的返回值并没有用到,猜想此函数的目的主要在把数组的每个元素遍历一下,即 走 walk 一遍.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值