Home >Backend Development >PHP Tutorial >Callback functions and arrays

Callback functions and arrays

不言
不言Original
2018-04-14 16:37:181877browse

The content shared with you in this article is about PHP callback functions and arrays, which has certain reference value. Friends in need can refer to

array_filter(), array_map(), Usage comparison of array_reduce(), array_walk()

array_filterUse the callback function to filter the cells in the array

Description: array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Pass each value in the array array to the callback function in turn. If the callback function returns true, the current value of the array array will be included in the returned result array, otherwise, it will not Return any value to the result array. The key names of the array remain unchanged.

Parameter description:

array:Array to be looped

##callback:Callback function used

If the callback function is not provided, all items in array will be deleted Entries with equivalent values ​​of FALSE.

#flag:DecisioncallbackReceived parameter form

  • ##ARRAY_FILTER_USE_KEY - callbackAccepts the key name as the only parameter

  • ##ARRAY_FILTER_USE_BOTH - callbackAccepts both key name and key value

Return value: Returns the filtered array.

Example 1:

function odd($var){    return($var & 1);}function even($var){    
return(!($var & 1));
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);echo "Odd :\n";print_r(array_filter($array1, "odd"));
echo "<br />Even:\n";
print_r(array_filter($array2, "even"));
结果:Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) 
Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 )
Analysis: & is PHP's AND operation, when the value in the array is passed in, the AND operation is performed based on the binary form and...0000 0001 (the number of 0s in front is related to the operating system, if you don't understand, you can fill in the basic knowledge). If the result is true, Then return the value passed in to the result array.

Example 2: If there is no callback function, if the value in the array is true, the value in the array will be returned to the result array

$entry = array(    0 => 'foo',    1 => false,    2 => -1,    3 => null,    4 => '');
print_r(array_filter($entry));
结果:Array ( [0] => foo [2] => -1 )
Example 3:

If there is only a key value, then The callback function only needs to receive a key value. If both key-value pairs are included, the first parameter receives the value, and the second parameter receives the key value

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
var_dump(array_filter($arr, function($k) {    
return $k == 'b';}, ARRAY_FILTER_USE_KEY));
var_dump(array_filter($arr, function($v, $k) {    
return $k == 'b' || $v == 4;}, ARRAY_FILTER_USE_BOTH));
结果:
D:\studySoftware\wamp64\www\test.php:
5:array (size=1)  'b' => int 2D:
\studySoftware\wamp64\www\test.php:
8:array (size=2)  'b' => int 2  'd' => int 4
array_map — 为数组的每个元素应用回调函数

说明:array array_map ( callable $callback , array $array1 [, array $... ] )

array_map(): Returns an array, which is applied to each element of array1 callbackThe array after the function. callback The number of function parameters and the number of arrays passed to array_map() must be the same.

Parameter description:

callback: Callback function, applied to each element in each array.

array1: array, traverse and run the callback function.

...数组列表,每个都遍历运行 callback 函数。

返回值:返回数组,包含 callback 函数处理之后 array1 的所有元素。

例1:

function cube($n){    
return($n * $n * $n);
}$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
结果:
Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )


例2:如果几个数组的元素数量不一致:空元素(null)会扩展短那个数组,直到长度和最长的数组一样。

function cube($n,$x){    
echo "n的值:{$n},x的值:{$x}<br />";    
return ($n + $x);}$a = array(1,2,3,4,5);
$b = array(10,20);
$c = array_map("cube",$a,$b);
print_r($c);
/*
结果:
n的值:
1,x的值:10n的值:
2,x的值:20n的值:
3,x的值:n的值:
4,x的值:n的值:
5,x的值:Array ( [0] => 11 [1] => 22 [2] => 3 [3] => 4 [4] => 5 ) 
*/

例3:此函数有个有趣的用法:传入 NULL 作为回调函数的名称,将创建多维数组(一个数组,内部包含数组。)

$a = array(1, 2, 3);
$b = array("one", "two", "three");
$c = array("uno", "dos", "tres");
$d = array_map(null, $a, $b, $c);
echo "<pre class="brush:php;toolbar:false">";
print_r($d);
echo "
";

结果如下:


例4:如果仅传入一个数组,键(key)会保留;传入多个数组,键(key)是整型数字的序列。

$arr = array("stringkey" => "value");
function cb1($a) {    
return array ($a);
}function cb2($a, $b) {    
return array ($a, $b);
}var_dump(array_map("cb1", $arr));
var_dump(array_map("cb2", $arr, $arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null, $arr, $arr));

结果如下:

array_reduceUse the callback function to iteratively reduce the array to a single value

Description: mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL## ] )

array_reduce() Apply the callback function callback iteratively to array Each cell in the array, thereby reducing the array to a single value.

Parameters:

array: Input array.

callbackmixed callback ( mixed $carry , mixed $item )

##        carry: Carries the value in the last iteration; if this iteration is the first time, then this value is initial.

item: carries the value of this iteration.

initialIf optional parameters are specified initial, this parameter will be used before processing starts, or when the processing ends and the array is empty, the last result (that is, when the parameter array is empty, initialAs the return value of array_reduce()).

官网例子:

function sum($carry, $item){    
$carry += $item;    
return $carry;
}
function product($carry, $item){    
$carry *= $item;    
return $carry;
}
$a = array(1, 2, 3, 4, 5);
$x = array();
var_dump(array_reduce($a, "sum")); 
// int(15)var_dump(array_reduce($a, "product", 10)); 
// int(1200), because: 10*1*2*3*4*5var_dump(array_reduce($x, "sum", "No data to reduce")); 
// string(17) "No data to reduce"

这里讨论array为空的情况:

function sum($carry, $item){    
echo "如果这里执行了,就打印...";    
return $carry;}$x = array();
print_r(array_reduce($x, "sum",array("a","b")));
//结果:
Array ( [0] => a [1] => b )

可以看出,当数组为空的时候,回调函数根本就没有执行,而是把initial作为array_reduce返回值


array_walk — 使用用户自定义函数对数组中的每个元素做回调处理

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

##Place the user-defined function funcname Applies to each cell in the array array.

array_walk() will not be affected by the array internal array pointer. array_walk() will traverse the entire array regardless of the position of the pointer.

Parameter description:

arrayInput array.

callback: Typically callback accepts two parameters. array The value of the parameter is used as the first one, and the key name is used as the second .

#Note:

If

callback needs to act directly on the values ​​in the array, specify the first parameter to callback as a reference. Any changes to these cells will also change the original array itself.

##Note

:

The number of parameters exceeds the expected number. If passed to a built-in function (such as strtolower()), a warning will be thrown, so it is not suitable as funcname.


Only the value of array can be changed. Users should not change the array itself in the callback function. Structure. For example, add/delete units, unset units, etc. If the array array_walk() acts on changes, the behavior of this function is undefined and unpredictable.


userdata: If the optional parameter userdata is provided, it will be passed to the callback as the third parameter funcname.


返回值:成功时返回 TRUE, 或者在失败时返回 FALSE


例子:

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana");
function test_alter(&$item1, $key, $prefix){    
echo "$item1=$key=$prefix<br/>";   
$item1 = "$prefix: $item1";
}function test_print($item2, $key){   
 echo "$key. $item2<br />\n";}echo "Before ...:<br />";
 array_walk($fruits, 'test_print');array_walk($fruits, 'test_alter', 'fruit');echo "... and after:<br />";
 array_walk($fruits, 'test_print');
 /*
 Before ...:
 d. lemona. orange
 b. bananalemon=d=fruitorange=a=fruitbanana=b=fruit... and after:
 d. fruit: 
 lemona. fruit: 
 orangeb. fruit: 
 banana
 */


           

The above is the detailed content of Callback functions and arrays. 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