In PHP, the array_map() function stands out as a versatile tool for transforming arrays by applying a user-defined function to each element. In this guide, we'll solve how to tackle multidimensional arrays effectively using array_map(). Our example will demonstrate solving a multidimensional array by applying a custom function to specific elements.
Consider a multidimensional array where each sub-array represents a set of values. The goal is to modify certain elements based on a condition, and for this task, we'll leverage the array_map() function. Let's dive into an example to elucidate the process:
<?php
function MyFunction($value){
if($value[0] == 'value 2'){
$value[1] = $value[1] * 2;
$value[2] = $value[2] * 3;
}
return $value;
}
$array =array(
array("value 1",100,96),
array("value 2",60,59),
array("value 3",110,100)
);
$array_map = array_map('MyFunction', $array);
print_r($array_map);
/*
::::OUTPUT::::
Array
(
[0] => Array
(
[0] => value 1
[1] => 100
[2] => 96
)
[1] => Array
(
[0] => value 2
[1] => 120
[2] => 177
)
[2] => Array
(
[0] => value 3
[1] => 110
[2] => 100
)
)
*/
?>
The function checks if the first element of the sub-array is 'value 2'. If true, it modifies the second element by doubling it (`$value[1] * 2`) and the third element by tripling it (`$value[2] * 3`).
`array_map('MyFunction', $array)` applies the custom function to each sub-array in `$array`.
Adjust the logic in `MyFunction` to suit your specific requirements. Target different conditions or elements for modification based on your use case.
`array_map()` can be combined with other array functions for more complex transformations. Explore other array functions like `array_filter()` or `array_reduce` based on your needs.