欢迎访问宙启技术站
智能推送

PHPFunction:array_map()–HowtoApplyaFunctiontoAllElementsofanArrayinPHP

发布时间:2023-09-23 21:35:55

The array_map() function is a built-in function in PHP that allows you to apply a specific function to every element of an array and return a new array with the modified values. It takes two arguments: the first argument is the function you want to apply, and the second argument is the array you want to iterate over.

Here is an example of how to use the array_map() function:

// Define a function to apply
function square($num) {
    return $num * $num;
}

// Define an array
$numbers = [1, 2, 3, 4, 5];

// Apply the function to all elements of the array
$squaredNumbers = array_map("square", $numbers);

// Output the modified array
print_r($squaredNumbers);

In this example, we define a function square() that takes a number as an argument and returns the square of that number. We also define an array $numbers containing some numeric values. We then use the array_map() function to apply the square() function to each element of the $numbers array. The result is stored in the variable $squaredNumbers.

The output of the above code will be:

Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

As you can see, the array_map() function applies the square() function to each element of the array and returns a new array $squaredNumbers with the modified values.

You can also apply anonymous functions (lambda functions) instead of named functions to the array_map() function. This allows you to define the function on the fly without having to declare it separately. Here is an example:

// Define an array
$numbers = [1, 2, 3, 4, 5];

// Apply an anonymous function to all elements of the array
$squaredNumbers = array_map(function($num) {
    return $num * $num;
}, $numbers);

// Output the modified array
print_r($squaredNumbers);

This example achieves the same result as the previous example, but instead of defining a separate square() function, we define an anonymous function directly inside the array_map() function.

In summary, the array_map() function in PHP allows you to apply a specific function to each element of an array and return a new array with the modified values. This is a convenient way to perform operations on array elements without having to use a loop.