search
HomeBackend DevelopmentPHP TutorialCallback functions and arrays

Callback functions and arrays

Apr 14, 2018 pm 04:37 PM
functionarray

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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor