


Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.
The difference between array_map, array_filter and array_reduce is: 1.array_map uniformly processes each element and returns a new array; 2.array_filter filters elements that meet the conditions, retains the original value or modifies the key value; 3.array_reduce condenses the array into a result. Specifically, array_map is suitable for transforming all elements in an array, such as squared operations to generate a new array; array_filter is used to filter out elements that meet the conditions, and supports default filtering of false values and custom callback judgments; array_reduce compresses the array into a single value through accumulation, such as summing or splicing strings, and the initial value can be customized or the first element is used by default. The three have clear uses, corresponding to modification, filtering and aggregation operations.
In PHP, array_map
, array_filter
and array_reduce
are three commonly used array processing functions. They can all be used in combination with callback functions to operate arrays, but their respective uses are different. Simply put:

-
array_map
: Process each element in the array and return a new array. -
array_filter
: Filter elements that meet the criteria, retain the original value or modify the key value. -
array_reduce
: "shrink" the array into a value, such as summing, splicing, etc.
Let’s take a look at their actual usage and differences below.
array_map
: Perform unified processing of each element
This function is suitable for situations where you want to perform some transformation on each element in the array. It will iterate over the array, pass each element to the callback function, and then collect the return values to form a new array.

Common usage examples:
$numbers = [1, 2, 3, 4]; $squared = array_map(fn($n) => $n * $n, $numbers); // Results: [1, 4, 9, 16]
- The callback function must have a return value, otherwise the position will become
null
. - Multiple arrays can be passed, and the callback parameters correspond one by one (for example, two arrays are added).
- The keys of the original array will be retained unless you pass multiple arrays and the keys are inconsistent, and then they will be merged according to the index.
array_filter
: Leave elements that comply with the rules
Use this function when you want to pick out certain elements that meet the criteria from the array. It won't change the value of the element (unless you actively change it in the callback), it just decides whether to stay or not.

Two ways to use:
- Only one parameter is passed : automatically filter out "false values" (such as
0
,false
,null
,''
). - Bring callback function : define the judgment logic yourself.
$numbers = [0, 1, 2, false, '', null, 3]; $result = array_filter($numbers); // Result: [1 => 1, 2 => 2, 6 => 3], leaving only the "true value" $even = array_filter($numbers, fn($n) => is_int($n) && $n % 2 === 0); // Filter out values that are integers and are even numbers
Notice:
- If you want to keep the original key name, remember to use
ARRAY_FILTER_USE_BOTH
flag. - If the callback function returns
true
, it will be retained, andfalse
it will be excluded.
array_reduce
: Concentrate the array into a result
This is the most flexible but also the easiest to misunderstand. It is not used to generate a new array, but to continuously "accumulate" the results and compress the entire array into a value, such as sum, string splicing, complex calculations, etc.
$numbers = [1, 2, 3, 4]; $sum = array_reduce($numbers, fn($carry, $item) => $carry $item, 0); // Results: 10
Key points:
-
$carry
is the result of the last time, the first time is the initial value (the third parameter). -
$item
is the element currently processed. - The initial value is optional. If it is not passed, the first element is defaulted to be the initial value and processed from the second one.
Let's give a slightly more complicated example:
$words = ['apple', 'banana', 'cherry']; $result = array_reduce($words, fn($str, $word) => $str . '-' . $word); // Result: 'apple-banana-cherry'
Basically that's it. Although these three functions can be used in conjunction with callbacks, they have clear responsibilities: map
changes each element, filter
picks out part of it, reduce
all into one result. When using it, you can write clearer and concise code according to the purpose.
The above is the detailed content of Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

This article discusses in depth how to use CASE statements to perform conditional aggregation in MySQL to achieve conditional summation and counting of specific fields. Through a practical subscription system case, it demonstrates how to dynamically calculate the total duration and number of events based on record status (such as "end" and "cancel"), thereby overcoming the limitations of traditional SUM functions that cannot meet the needs of complex conditional aggregation. The tutorial analyzes the application of CASE statements in SUM functions in detail and emphasizes the importance of COALESCE when dealing with the possible NULL values of LEFT JOIN.

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.
