Sobes.tech
Junior — Middle

Do you understand how a function call is made when using array_map() with a callback?

sobes.tech AI

Answer from AI

The array_map() function in PHP takes a callback function and one or more arrays. It applies the callback to each element of the array(s) and returns a new array with the results.

When you pass a callback to array_map(), PHP calls this function for each element of the array, passing the corresponding values from each array by index.

Example:

function square($n) {
    return $n * $n;
}

$numbers = [1, 2, 3, 4];
$squares = array_map('square', $numbers);
print_r($squares); // Outputs: [1, 4, 9, 16]

If you pass multiple arrays, the callback should accept as many arguments as there are arrays:

function sum($a, $b) {
    return $a + $b;
}

$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$sums = array_map('sum', $arr1, $arr2);
print_r($sums); // Outputs: [5, 7, 9]

Thus, array_map() calls the callback for each set of elements from the arrays, forming a new array from the results of these calls.

Do you understand how a function call is made when… - sobes.tech