js

Thursday, December 7, 2023

Can you provide an explanation of array_map() function in PHP along with an illustrative example?

 Q. Can you provide an explanation of array_map() function in PHP along with an illustrative example?
Asnwer:
The array_map() function in PHP is used to apply a callback function to each element of one or more arrays. It takes one or more arrays as input and applies the specified callback function to each corresponding element of the arrays. The result is a new array containing the modified elements.

Here's the basic syntax of array_map():
array_map(callback, array1, array2, ...);

callback: The callback function to apply to each element.
array1, array2, ...: The arrays to process.

Now, let's look at an illustrative example to understand how array_map() works:
<?php
// Define a callback function
function square($num) {
    return $num * $num;
}

// An array of numbers
$numbers = [1, 2, 3, 4, 5];

// Use array_map() to apply the square function to each element in $numbers
$squaredNumbers = array_map('square', $numbers);

// Display the original and modified arrays
print_r($numbers);
print_r($squaredNumbers);
?>

In this example:

We define a callback function named square that takes a number and returns its square.
We have an array of numbers called $numbers.
We use array_map() to apply the square function to each element in the $numbers array, resulting in a new array $squaredNumbers.
We then use print_r() to display both the original $numbers array and the modified $squaredNumbers array.
The output will be:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

As you can see, array_map() applied the square function to each element in the $numbers array, resulting in a new array with the squared values.

No comments:

Post a Comment