PHP, being a popular programming language, offers a range of built-in functions to simplify development. One such useful function is array_map(). This function allows you to apply a callback function to one or more arrays and returns a new array containing the modified elements. In this article, we'll go over how to use array_map() and demonstrate its functionality with examples.
The function signature of array_map() is as follows:
array_map ( callable $callback , array $array1 [, array $... ] ) : array
Return Value: array_map() returns a new array with the elements modified by the callback function.
The following example demonstrates how to use array_map() to convert each element of an array to uppercase:
function convert_to_uppercase($value) {
return strtoupper($value);
}
$names = array("john", "james", "jane", "julie");
$names_uppercase = array_map("convert_to_uppercase", $names);
print_r($names_uppercase);
Output:
Array
(
[0] => JOHN
[1] => JAMES
[2] => JANE
[3] => JULIE
)
As shown above, array_map() successfully converts each element of the $names array to uppercase and stores the result in the $names_uppercase array.
You can also use an anonymous function as a callback. The following example shows how to double the value of each element in an array:
$numbers = array(1, 2, 3, 4, 5);
$doubled_numbers = array_map(function($value) {
return $value * 2;
}, $numbers);
print_r($doubled_numbers);
Output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
By using an anonymous function, array_map() doubles each element of the $numbers array and stores the result in the $doubled_numbers array.
In real-world development, array_map() is commonly used for transforming, filtering, or manipulating arrays. Whether you're cleaning data or performing simple mathematical operations, array_map() is a powerful tool for handling arrays efficiently.
array_map() is a very useful function in PHP that allows you to apply a callback function to each element of an array and return a new array. Its flexibility and simplicity make it an invaluable tool for many real-world scenarios. Mastering array_map() can help you handle array manipulation more efficiently, ultimately improving your development workflow.
Related Tags:
array_map