BobbyeM71hxwHow can you reduce writing foreach() cycles?

Php 5.3 – helps you to reduce writing foreach() cycles

At least in php. Php 5.3 has a solution that will reduce the average number of iteration structures you need to write: closures applied by plain old array functions.

There are some array functions which have already been supported at least from Php 4, and that take as an argument a callback whose formal parameters have to be one or two elements of the array. Let’s talk about array_map(), array_reduce(), array_filter() and uasort() (or similar custom sorting function.) These functions abstract away a foreach() cycle by applying a particular computation to all the elements of an array.

Back in Php 4 and Php 5.2, specifying a callback was cumbersome: you had to define an external function and then passing its name as a string; or passing an array containing an object or the class name plus the method name in case of a public (possibly static) method.

In Php 5.3, callbacks may also be specified as anonymous functions, defined in the middle of other code. These closures are first class citizens, and are treated as you would treat a variable, by passing it around as a method parameter. While I am not a fan of mixing up object-oriented and functional programming, closures can be a time saver which capture very well the intent of low-level processing code, avoiding the foreach() noise.

array_map() applies a function to every element of an array,
// returning the result
$square = function($number) {
return $number * $number;
};
$squared = array_map($square, $primeNumbers);
echo “The squares of those prime numbers are: “,
implode(‘, ‘, $squared), “\n”;

// array_reduce() applies a function recursively to pair
// of elements, reducing the array to a single value.
// there is the native array_sum(), but the application of
// a custom function is the interesting part
$sum = function($a, $b) {
return $a + $b;
};
$total = array_reduce($primeNumbers, $sum);
echo “The sum of those prime numbers is “, $total, “.\n”;

// array_filter() produces an array containing
// the elements that satisfy the given predicate
$even = function($number) {
return $number % 2 == 0;
};
$evenPrimes = array_filter($primeNumbers, $even);
echo “The even prime numbers are: “,
implode(‘, ‘, $evenPrimes), “.\n”;

// uasort() customize the sorting by value,
// maintaining the association with keys
// there is the native asort(), but again the customization
// of the function is more interesting
$compare = function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
};
uasort($primeNumbers, $compare);
echo “The given numbers in descending order are: “,
implode(‘, ‘, $primeNumbers), “.\n”;

http://www.all1Press.com

http://www.all1tunes.com

http://www.all1sourcetech.com

Tags: , , , , ,