xxxxxxxxxx
$numbers = [1, 2, 3, 4, 5];
// Define a callback function to double each number
function double($value) {
return $value * 2;
}
// Apply the callback to each element using array_map()
$doubledNumbers = array_map('double', $numbers);
// Output the new array with doubled values
print_r($doubledNumbers);
xxxxxxxxxx
<?php
function my_callback($item) {
return strlen($item);
}
$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>
xxxxxxxxxx
$test_array = array("first_key" => "first_value",
"second_key" => "second_value");
array_walk($test_array, function(&$a, $b) { $a = "$b loves $a"; });
var_dump($test_array);
// array(2) {
// ["first_key"]=>
// string(27) "first_key loves first_value"
// ["second_key"]=>
// string(29) "second_key loves second_value"
// }
xxxxxxxxxx
array_map ( callable $callback , array $array1 [, array $ ] ) : array
xxxxxxxxxx
<?php
function cube($n)
{
return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
?>
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
array_map — Applies the callback to the elements of the given arrays
xxxxxxxxxx
array_map(?callable $callback, array $array, array $arrays): array
array_map() returns an array containing the results of applying the callback to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback. The number of parameters that the callback function accepts should match the number of arrays passed to array_map(). Excess input arrays are ignored. An ArgumentCountError is thrown if an insufficient number of arguments is provided.
callback
A callable to run for each element in each array.
null can be passed as a value to callback to perform a zip operation on multiple arrays. If only array is provided, array_map() will return the input array.
array
An array to run through the callback function.
arrays
Supplementary variable list of array arguments to run through the callback function.
xxxxxxxxxx
<?php
// Example array
$numbers = [1, 2, 3, 4, 5];
// Callback function to double each number
function double($num)
{
return $num * 2;
}
// Map the array using the callback function
$doubledNumbers = array_map("double", $numbers);
// Output the mapped array
print_r($doubledNumbers);
?>
xxxxxxxxxx
<?php
function cube($n)
{
return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
?>
xxxxxxxxxx
PHP function array_map(?callable $callback, array $array, array $arrays) array
-----------------------------------------------------------------------------
Applies the callback to the elements of the given arrays.
Parameters:
callable|null--$callback--Callback function to run for each element in each array.
array--$array--An array to run through the callback function.
array--$arrays--[optional]
Returns: an array containing all the elements of arr1 after applying the callback function to each one.