Table of Contents
array_map : Perform unified processing of each element
array_filter : Leave elements that comply with the rules
array_reduce : Concentrate the array into a result
Home Backend Development PHP Tutorial Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.

Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.

Jul 08, 2025 am 01:08 AM

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.

Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.

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:

Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.
  • 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.

Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.

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.

Describe the differences between `array_map`, `array_filter`, and `array_reduce` in php.

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, and false 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!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

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

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

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

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

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

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

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

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

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

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

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

MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields Sep 16, 2025 pm 02:39 PM

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.

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

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

See all articles