Home >Backend Development >PHP Tutorial >php array_walk() array function usage instructions

php array_walk() array function usage instructions

怪我咯
怪我咯Original
2017-07-06 10:58:061332browse

Functionarray_walk(): Single arrayCallback function---Apply user function to each member in the array

The code is as follows:

/*函数array_walk():单一数组回调函数---对数组中的每个成员应用用户函数 
* 1、语法:bool array_walk ( array &array, callback funcname [, mixed $userdata] ) 
* 2、描述:如果成功则返回 TRUE,失败则返回 FALSE 
* 3、注意事项: 
* 3.1、$funcname是用户自己 定义的回调函数,接受2个参数,第一个参数为数组$array的值,第二个参数为 
* 数组$array的键名,如果提供第三个参数$userdata,将作为第三个参数传递给回调函数$funcname 
* 3.2、使用回调函数可以直接更改数组各个单元的值,但更改各个键名是无效的 
* 3.3、该函数 不会受到 array 内部数组指针的影响。array_walk() 会遍历整个数组而不管指针 
* 的位置 
* 3.4、用户不应在回调函数中改变该数组本身,例如增加/删除单元,unset 单元等等,如果 array_walk() 
* 作用的数组改变了,则此函数的的行为未经定义,且不可预期。 
*/ 
$words=array("l"=>"lemon","o"=>"orange","b"=>"banana","a"=>"apple"); 
//定义一个回调函数,输出数组元素 
function words_print($value,$key,$prefix){ 
echo "$prefix:$key=>$value<br>\n"; 
} 
//定义一个回调函数直接改变元素的值 
function words_alter(&$value,$key){ 
$value=ucfirst($value); 
$key=strtoupper(key); 
} 
//输出元素的值 
array_walk($words,&#39;words_print&#39;,&#39;words&#39;); 
//改变元素的值 
array_walk($words,&#39;words_alter&#39;); 
echo "<pre class="brush:php;toolbar:false">"; 
print_r($words); 
echo "
";

The operation effect is as follows:
php array_walk() array function usage instructions

The above is the detailed content of php array_walk() array function usage instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn