★ wanayoo — archive 1999 http://fr.php.net/manual/fr/function.array-map.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<array_keysarray_merge_recursive>
view the version of this page
Last updated: Sun, 20 Apr 2003

array_map

(PHP 4 >= 4.0.6)

array_map -- Applique sur fonction sur des tableaux

Description

array array_map ( mixed callback, array arr1 [, array ...])

array_map() retourne un tableau contenant tous les éléments du tableau arr1, après leur avoir appliqué la fonction callback. Le nombre de paramètres de la fonction callback doit être égal au nombre de tableaux passés dans la fonction array_map().

Exemple 1. Exemple avec array_map()

<?php
  function cube($n) {
      return $n*$n*$n;
  }
  $a = array(1, 2, 3, 4, 5);
  $b = array_map("cube", $a);
?>

Cela conduit à ce que la variable $b contienne :
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Exemple 2. array_map() - utilisation de plusieurs tableaux

<?php
  function parle_espagnol($n, $m) {
      return "Le nombre $n se dit $m en espagnol";
  }

  function map_espagnol($n, $m) {
   return array($n => $m);
  }

  $a = array(1, 2, 3, 4, 5);
  $b = array("uno", "dos", "tres", "cuatro", "cinco");
  $c = array_map("parle_espagnol", $a, $b);
  print_r($c);
?>

Cela va afficher :
// Contenu de $c
Array
(
    [0] => Le nombre 1 se dit uno en espagnol
    [1] => Le nombre 2 se dit dos en espagnol
    [2] => Le nombre 3 se dit tres en espagnol
    [3] => Le nombre 4 se dit cuatro en espagnol
    [4] => Le nombre 5 se dit cinco en espagnol
)

// Contenu de $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Généralement, lors de l'utilisation de plusieurs tableaux, ils doivent être d'égale longueur, car la fonction de callback est appliqué de manière similaire à tous les tableaux. Si les tableaux sont de taille inégales, les plus petits seront complétés avec des éléments vides.

Une utilisation intéressante de cette fonction est la construction de tableaux de tableaux, facilement réalisé en passant la valeur NULL comme nom de fonction de callback.

Exemple 3. Création d'un tableau de tableaux

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array("un", "deux","trois","quatre","cinq");

$d = array_map(null, $a, $b, $c, $d);
print_r($d);
?>

Le programme ci-dessus va afficher :
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
            [3] => un
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
            [3] => deux
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
            [3] => trois
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
            [3] => quatre
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
            [3] => cinq
        )

)

Voir aussi array_filter(), array_reduce() et array_walk().



User Contributed Notes
array_map
add a note
bishop
26-Mar-2002 10:33

Sometimes you might be interested in performing a "deep" map, where you apply the callback to all elements in the array, even if the elements are stuck deep inside of some array(array(array(...))) business.

Here's an example PHP4 function that handles this case, with a little bit more flexible (and potentially more error-prone) callback parameter:

function deepmap($cb, $x) {

   if (is_array($x)) {
       $it = array();
       foreach ($x as $k => $v) {
           $it["$k"] = deepmap($cb, $x["$k"]);
       }
       return $it;
   } else {
       $cmd = "return (" .
              str_replace('$__', $x, $cb) .
              ");";
      return eval($cmd);
   }

}

So, you could do, for example:

$some_odds  = array(1, 3, 5);
$some_evens = array(0, 2, 4, 6);
$some_nums  = array($some_odds, array($some_evens));

deepmap('pow($__, 2)', $some_odds);
deepmap('pow($__, 2)', $some_nums);

Both examples square each element of the arrays, making sure to keep the array structure intact.

Note that the callback function needs to be a) quoted, and b) include the special string $__ (dollar double underscore); deepmap replaces $__ in the function call with whatever the current element is.

shane at sell d.t com
22-May-2002 10:26

With the help of an associate of mine, I discovered that array_map, like array_filter, takes an array with an object reference and method as the callback.

ie:

array_map( array($this, "callback"), $arr );

dan at mojavelinux dot com
15-Jun-2002 05:07

Here is a better, more true version of a deep array_map.  The only negative of this function is that the array is passed by reference, so just be aware of that. (patches welcome)

function array_map_deep(&$in_array, $in_func, $in_args = array(), $in_index = 1) {
   // fix people from messing up the index of the value
   if ($in_index < 1) {
      $in_index = 1;
   }

   foreach (array_keys($in_array) as $key) {
       // we need a reference, not a copy, normal foreach won't do
       $value =& $in_array[$key];
       // we need to copy args because we are doing
       // manipulation on it farther down
       $args = $in_args;
       if (is_array($value)) {
          array_map_deep($value, $in_func, $in_args, $in_index);
       }
     else {
           array_splice($args, $in_index - 1, $in_index - 1, $value);
           $value = call_user_func_array($in_func, $args);
       }
   }
   
   return $in_array;
}

This is a neat function because you can pass an array, a function, and an array of parameters, and finally, and index of where in the array of parameters for the callback function the contents you are mapping should get replaced.  This index is human based (starts at 1), and can be used in something like a preg_replace callback, where the contents must be the 3rd index.  Enjoy!

php1@goelette (TLD=net)
28-Oct-2002 07:44

If you want to call back a function in a class, you cannot use:
array_map('class_function', $my_array)

Use:
array_map(array($this, 'class_function'), $my_array)

NetVicious IN hotmail_com
24-Nov-2002 01:00

Get the max length in an array of strings

function maxLength($str) {
  return strlen($str);
}

$maxLen = max(array_map("maxLength", $myArray));

stephen at mu dot com dot au
07-Jan-2003 05:02

A note when doing something allong the lines of:

class foo {
var $var;
 function bar() {
    array_map(array($this, "baz"), array(1,2,3));
 }

 function baz($arg) {
 $this->var = $this->var + $arg;
 }
}

This will *not* work as expected. You need to pass $this by reference as with:

array_map(array(&$this, "baz"), array(1,2,3));

or you'll be making a copy of the object each time, changing a value, then throwing the result away.

add a note

<array_keysarray_merge_recursive>
 Last updated: Sun, 20 Apr 2003
show source | credits | stats | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Mon May 12 05:09:11 2003 CEST