Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

Advanced Array Operations?

Advanced array operations like map(), filter(), and reduce() are powerful tools in PHP (and many other programming languages) for performing transformations, filtering, and aggregations on arrays. These functions are commonly associated with functional programming paradigms and are essential for writing clean, concise, and expressive code.

Let’s explore each of these array operations:

map():

Functionality: The map() function applies a callback function to each element of the array and returns a new array containing the results of applying the callback to each element.

Usage: array_map(callback $callback , array $array1 [, array $… ]): array

Example:

PHP
<?php

$numbers = [1, 2, 3, 4, 5];

$squaredNumbers = array_map(function($x) {

    return $x * $x;

}, $numbers);

print_r($squaredNumbers); // Outputs: [1, 4, 9, 16, 25]

?>

filter():

Functionality: The filter() function filters elements of an array using a callback function. It returns a new array containing only the elements for which the callback function returns true.

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

Example:

PHP
<?php

$numbers = [1, 2, 3, 4, 5];

$evenNumbers = array_filter($numbers, function($x) {

    return $x % 2 == 0;

});

print_r($evenNumbers); // Outputs: [2, 4]

reduce():

Functionality: The reduce() function applies a callback function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

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

Example:

PHP
<?php

$numbers = [1, 2, 3, 4, 5];

$sum = array_reduce($numbers, function($accumulator, $currentValue) {

    return $accumulator + $currentValue;

}, 0);

echo $sum; // Outputs: 15

?>

These array operations allow for concise and expressive code that can manipulate arrays in various ways, such as transforming elements, filtering them based on certain conditions, or aggregating them into a single value. They are essential tools in modern PHP development, especially in functional programming paradigms. Understanding and mastering these functions can greatly enhance your ability to work with arrays and write efficient and maintainable PHP code.