Articles

The month of PHP functions : working with array without loops

  • Ecrit par Damien Seguy
  • dimanche 29 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


Apply a filter to a variable is pretty simple. Applying the same filter to a mass of variables requires a loop. Or just a function for arrays.


array_filter() will be our stop. array_filter() remove all values from an array, based on a user function. The function will get each element of the array as argument, and return true to keep it in the array. False will unset the value.

<?php
 
 
$array = array_flip(range('a', 'f'));
 
 
$filtered = array_filter( $array,'filter');
print_r($filtered);
 
 
 
function filter($x) {
    return $x % 2;
}
?>
 
 
Array
(
    [b] => 1
    [d] => 3
    [f] => 5
)

Besides removing data, you may also modify elements in an array without using a loop. This a great way to hide a loop, and to force yourself to separate your transformation into a function. This function may actually have more than one argument, and will return the new value for the resulting array of array_map(). Look at the example :

<?php
$array = array_flip(range('a', 'f'));
 
 
$transformed = array_map('transform', $array);
print_r($transformed);
 
 
function transform($x) {
    if ($x < 2) {
        return $x. " bread";
    } else {
        return $x. " breads";
    }
}
?>

To tranform an associative array, you need another trick :
<?php
$array = array_flip(range('a', 'f'));
 
 
$keys = array_keys($array);
$values = array_values($array);
 
 
$middle = array_map('transform', $keys, $values);
$transformed = array_combine($keys, $middle);
print_r($transformed);
 
 
function transform($key, $value) {
    return "The key associated to $value is $key";
}
?>

The transformation function may take several arguments : then, you have to give several arrays to array_map() so that to match the number of arguments needed. If you give too many arrays, the extra one will be passed, and you'll need func_get_args() to reach them. If you feed array_map() with insufficient arrays, the function will display an alert.

array_walk() provides the same functionnality than array_map(), but in another way. If array_map() returns an array, array_walk() works directly on the array.

The arguments are also in the reverse order : the function is now second, and the transformed array is first. array_walk() will also send to the function any arguments that are passed as third argument. With array_map(), you would have to rely on array_fill() to generate an array filled with the same value.

Also, the key will be send as second argument of the transformation function. All extra argument given to array_walk() will be send as third argument and so on... Here is the previous example, refactored with array_walk().

<?php
$array = array_flip(range('a', 'f'));
 
 
array_walk($array, 'transforme');
print_r($array);
 
 
function transforme(&amp;$value, $key) {
    $value = "La cl&eacute; $key est associ&eacute;e a la valeur $value";
}
?>

Keep in mind
  • It is possible to give only an array to array_filter(), and this will prune all false equivalent values (empty string, 0 values, empty arrays...)
  • The transformation function of array_map() will be applied to the largest number of elements possible. All missing values from other arrays will be null values.
  • array_walk is capable to work with multi-dimensionnal array, with array_walk_recursive().

< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter