Callback functions and arrays
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_filter — Use 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
- callback
Accepts 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 )
$entry = array( 0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => ''); print_r(array_filter($entry)); 结果:Array ( [0] => foo [2] => -1 )
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
callback
The 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_reduce — Use 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.
callback:mixed 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.
initial:If 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:
array: Input 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:
Ifcallback 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 Only the value of userdata: If the optional parameter 返回值:成功时返回 例子:
funcname
. 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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.
