Using closure
<?php
// Our closure
$double = function($a) {
return $a * 2;
};
// This is our range of numbers
$numbers = range(1, 5);
// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);
print implode(' ', $new_numbers);
?>
To solve the following closure program without using callback and closure.
We can achieve the same result as the array_map()
example without using array_map()
and callbacks by using a traditional for
loop. Here's how you can do it:
// A function to double a number
function double($num) {
return $num * 2;
}
// An array of numbers
$numbers = [1, 2, 3, 4, 5];
// Create a new array to store the doubled values
$new_numbers = [];
// Loop through each element of the $numbers array and double the value
for ($i = 0; $i < count($numbers); $i++) {
$new_numbers[] = double($numbers[$i]);
}
print_r($new_numbers);
Output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
In this alternative approach, we manually loop through each element of the $numbers
array using a for
loop. We call the double()
function on each element and add the doubled value to the $new_numbers
array using the []
syntax to push the value to the end of the array.
While using array_map()
and callbacks can make the code more concise and expressive, the for
loop method is an alternative when you want to avoid using callbacks or prefer a more traditional looping approach. Both methods achieve the same result in this case.