数组 函数
在线手册:中文 英文
PHP手册

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map 将回调函数作用到给定数组的单元上

说明

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

array_map() 返回一个数组,该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

Example #1 array_map() 例子

<?php
function cube($n)
{
    return(
$n $n $n);
}

$a = array(12345);
$b array_map("cube"$a);
print_r($b);
?>

这使得 $b 成为:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example #2 array_map() - 使用更多的数组

<?php
function show_Spanish($n$m)
{
    return(
"The number $n is called $m in Spanish");
}

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

$a = array(12345);
$b = array("uno""dos""tres""cuatro""cinco");

$c array_map("show_Spanish"$a$b);
print_r($c);

$d array_map("map_Spanish"$a $b);
print_r($d);
?>

以上例程会输出:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

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

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

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

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

)

通常使用了两个或更多数组时,它们的长度应该相同,因为回调函数是平行作用于相应的单元上的。如果数组的长度不同,则最短的一个将被用空的单元扩充。

本函数一个有趣的用法是构造一个数组的数组,这可以很容易的通过用 NULL 作为回调函数名来实现。

Example #3 建立一个数组的数组

<?php
$a 
= array(12345);
$b = array("one""two""three""four""five");
$c = array("uno""dos""tres""cuatro""cinco");

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

以上例程会输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

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

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

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

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

)

参见 array_filter()array_reduce()array_walk()callback 类型的信息。

参数

callback

Callback function to run for each element in each array.

arr1

An array to run through the callback function.

array

Variable list of array arguments to run through the callback function.

返回值

Returns an array containing all the elements of arr1 after applying the callback function to each one.

范例

Example #4 array_map() example

<?php
function cube($n)
{
    return(
$n $n $n);
}

$a = array(12345);
$b array_map("cube"$a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example #5 array_map() using a lambda function (as of PHP 5.3.0)

<?php
$func 
= function($value) {
    return 
$value 2;
};

print_r(array_map($funcrange(15)));
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example #6 array_map() - using more arrays

<?php
function show_Spanish($n$m)
{
    return(
"The number $n is called $m in Spanish");
}

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

$a = array(12345);
$b = array("uno""dos""tres""cuatro""cinco");

$c array_map("show_Spanish"$a$b);
print_r($c);

$d array_map("map_Spanish"$a $b);
print_r($d);
?>

以上例程会输出:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

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

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

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

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

)

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

Example #7 Creating an array of arrays

<?php
$a 
= array(12345);
$b = array("one""two""three""four""five");
$c = array("uno""dos""tres""cuatro""cinco");

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

以上例程会输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

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

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

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

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

)

If the array argument contains string keys then the returned array will contain string keys if and only if exactly one array is passed. If more than one argument is passed then the returned array always has integer keys.

Example #8 array_map() - with string keys

<?php
$arr 
= array("stringkey" => "value");
function 
cb1($a) {
    return array (
$a);
}
function 
cb2($a$b) {
    return array (
$a$b);
}
var_dump(array_map("cb1"$arr));
var_dump(array_map("cb2"$arr$arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null$arr$arr));
?>

以上例程会输出:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

参见


数组 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 将回调函数作用到给定数组的单元上

用户评论:

qeremy (07-Mar-2012 06:35)

An alternative for recursive mapping;

<?php
function array_map_recursive($fn, $arr) {
   
$rarr = array();
    foreach (
$arr as $k => $v) {
       
$rarr[$k] = is_array($v)
            ?
array_map_recursive($fn, $v)
            :
$fn($v); // or call_user_func($fn, $v)
   
}
    return
$rarr;
}

function
sqr($x) {
    return
"$x ^ 2 = ". ($x * $x);
}

$a = array(1, 2, 3, array(4, array(5)));
$b = array_map_recursive("sqr", $a);
print_r($b);
?>

Array
(
    [0] => 1 ^ 2 = 1
    [1] => 2 ^ 2 = 4
    [2] => 3 ^ 2 = 9
    [3] => Array
        (
            [0] => 4 ^ 2 = 16
            [1] => Array
                (
                    [0] => 5 ^ 2 = 25
                )

        )

)

qeremy [atta] gmail [dotta] com (02-Mar-2012 07:33)

@ erik dot stetina at gmail dot com 27-Sep-2011 03:05;

<?php
function array_prefix_values($prefix, $array) {
    return
array_map(function($str) use($prefix) {
        return
$prefix . $str;
    },
$array);
}
?>

gmail.com@mspreij (27-Feb-2012 06:48)

Hope I'm not late to the party, here's my function to apply array_map to the *keys* of an array.
Extra array arguments will be used for the callback function's parameters just like with array_map, with the difference that a string is also allowed: it will just be used to create an array of appropriate length with as each value that string. Arrays are left alone (and will be padded with nulls by array_map as needed).

<?php

//_________________________________________________
// array_map_keys($callback, $array, [$args, ..]) /
function array_map_keys($callback, $array /* [, $args ..] */) {
 
$args = func_get_args();
  if (!
is_callable($callback)) trigger_error("first argument (callback) is not a valid function", E_USER_ERROR);
  if (!
is_array($array)) trigger_error("second argument must be an array", E_USER_ERROR);
 
$args[1] = array_keys($array);
 
// If any additional arguments are not arrays, assume that value is wanted for every $array item.
  // array_map() will pad shorter arrays with Null values
 
for ($i=2; $i < count($args); $i++) {
    if (!
is_array($args[$i])) {
     
$args[$i] = array_fill(0, count($array), $args[$i]);
    }
  }
  return
array_combine(call_user_func_array('array_map', $args), $array);
}

// Some examples:

$arr = array('foo'=>123, 'bar'=>456);

// simply uppercase keys:
var_dump(array_map_keys('strtoupper', $arr));
// or..
var_dump(array_map_keys(function($input) {return strtoupper($input);}, $arr));
// >> array(2) { ["FOO"]=>int(123) , ["BAR"]=> int(456) }

// Add a prefix 'myvar_':
var_dump(array_map_keys(function($input, $prefix) {return $prefix.$input;}, $arr, 'myvar_'));
// >> array(2) { ["myvar_foo"]=>int(123) , ["myvar_bar"]=>int(456) }

// Apart from the (static string) prefix, we also number them:
$arr = array('foo'=>123, 'bar'=>456, 'bazz'=>789, 'yadda'=>'0AB');
var_dump(array_map_keys(function($input, $middle, $number) {return $number.':'.$middle.$input;}, $arr, 'myvar_', range(1, count($arr))));
// >> array(4) { ["1:myvar_foo"]=>int(123) , ["2:myvar_bar"]=>int(456) , ["3:myvar_bazz"]=>int(789) , ["4:myvar_yadda"]=>string(3) "0AB" }

?>

php/hotblocks/nl (28-Nov-2011 01:00)

Note that the $arr argument has to be an array, not just a Traversable/Iterator.

For instance this won't work:

<?php

$documents
= $mongo->db->collection->find();
// $documents is Traversable by foreach

$ids = array_map(function($document) {
  return
$document['_id'];
},
$objects);
// $ids will now be NULL, because $documents wasn't an Array

?>

A solution is to first use iterator_to_array():

<?php

$ids
= array_map(function($document) {
  return
$document['_id'];
},
iterator_to_array($objects));
// $ids will now be an array of ['_id']s

?>

But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one cycle and a lot of freedom (and in the same scope).

erik dot stetina at gmail dot com (27-Sep-2011 11:05)

function to prefix given string to each element of an array:

<?php
function array_prefix_values($prefix, $array)
{
 
$callback = create_function('$str','return "'.$prefix.'".$str;');
  return
array_map($callback,$array);
}
?>

usage:

<?php
$dir
= "./css/";
$files = scandir($dir);
$files = array_prefix_values($dir,$files);
print_r($files);
?>

output:

(
    [0] => ./css/.
    [1] => ./css/..
    [2] => ./css/default.css
    [4] => ./css/helper.css
    [6] => ./css/page_layout.css
)

spark at limao dot com dot br (08-Sep-2011 03:48)

it's a usefull way to filter user input through get and post request arrays:

<?php
    $get
= array_map("addslashes",$_GET);
?>

gordon dot mcvey at ntlworld dot com (28-Jan-2011 01:11)

You can use array_map with PHP native functions as well as user functions.  This is very handy if you need to sanitize arrays. 

<?php

$integers
= array_map ('intval', $integers);
$safeStrings = array_map ('mysql_real_escape_string', $unsafeStrings);

?>

pike-php at kw dot nl (11-Jan-2011 02:04)

If you're looking for a way to flatten multimaps, look at this:
<?php
   
    $multimap
= array(
        array(
"name"=>"value1"),
        array(
"name"=>"value2"),
        array(
"name"=>"value3")
    );
   
$flatmap = array_map("array_pop",$multimap);
   
print_r($flatmap);
?>

Output:
Array
(
    [0] => value1
    [1] => value2
    [2] => value3
)

brendan DOT caffrey AT me DOT com (10-Jul-2010 11:42)

Something that had me confused:

<?php
namespace test;

class
Callback
{
    static function
add($a) { return $a + 1; }
}

$array = array(0, 1, 2);
array_map(array('Callback', 'add'), $array); // will not work, even though you're calling this in the test namespace
array_map(array('test\Callback', 'add'), $array); // will work
?>

virtual dot greg at gmail dot com (05-Mar-2010 11:07)

PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly.

<?php
$data
= array(
        array(
'id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
        array(
'id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
        array(
'id' => 3, 'name' => 'James', 'position' => 'Director')
);

$names = array_map(
        function(
$person) { return $person['name']; },
       
$data
);

print_r($names);
?>

This was possible (although not recommended) in prior versions of PHP 5, via create_function().

<?php
$names
= array_map(
       
create_function('$person', 'return $person["name"];'),
       
$data
);
?>

You're less likely to catch errors in the latter version because the code is passed as string arguments.

These are alternatives to using a foreach:

<?php
$names
= array();

foreach (
$data as $row) {
       
$names[] = $row['name'];
}
?>

kelly m (17-Feb-2010 10:28)

I realize this function is easy enough to make, but this is a faster version (twice the speed) of [a function] which I find incredibly useful.

<?php
function array_pluck($key, $input) {
    if (
is_array($key) || !is_array($input)) return array();
   
$array = array();
    foreach(
$input as $v) {
        if(
array_key_exists($key, $v)) $array[]=$v[$key];
    }
    return
$array;
}
?>

Usage:

<?php $ids = array_pluck('id', $users); ?>

onassar at gmail dot com (14-Oct-2009 03:06)

Fixed a bug with array recursion.

<?php
       
/**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes. Note that this costs a descent amount more memory (eg. 1.5k per call)
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
       
function arrayMap($callback,$arr1) {
           
$results       =    array();
           
$args          =    array();
            if(
func_num_args()>2)
               
$args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach(
$arr1 as $key=>$value) {
               
$temp    =    $args;
               
array_unshift($temp,$value);
                if(
is_array($value)) {
                   
array_unshift($temp,$callback);
                   
$results[$key]    =    call_user_func_array(array('self','arrayMap'),$temp);
                } else {
                   
$results[$key]    =    call_user_func_array($callback,$temp);
                }
            }
            return
$results;
        }
?>

onassar at gmail dot com (11-Oct-2009 11:33)

Wrote up my own key preservation function for array mapping. It allows n arguments to be passed, and should be easy enough to follow if you need to make any mods. If you've got any thoughts let me know.

<?php
       
/**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes.
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
       
function arrayMap($callback,$arr1) {
           
$results       =    array();
           
$args          =    array();
            if(
func_num_args()>2)
               
$args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach(
$arr1 as $key=>$value) {
                if(
is_array($value)) {
                   
array_unshift($args,$value);
                   
array_unshift($args,$callback);
                   
$results[$key]    =    call_user_func_array(array('self','arrayMap'),$args);
                }
                else {
                   
array_unshift($args,$value);
                   
$results[$key]    =    call_user_func_array($callback,$args);
                }
            }
            return
$results;
        }
?>

macnimble at gmail dot com (10-Sep-2009 08:27)

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster:

<?php
function array_prefix_keys ()
{
 
$args = func_get_args();
 
$prefix = array_shift($args);
 
$func = create_function('$p,$k','return "$p{$k}";');
  foreach (
$args AS $key => $array):
   
$args[$key] = array_combine( array_map( $func
                                         
, array_fill(0,count($array),$prefix)
                                          ,
array_keys($array)
                                          )
                               ,
array_values($array)
                               );
  endforeach;
  return
$args;
}
$array1 = array(
 
'id'     => 1,
 
'title'  => 'about-us',
 
'author' => 'Bill Brown',
 
'dated'  => '2009-SEP-15'
);
$array2 = array(
 
'id'     => 2,
 
'title'  => 'about-them',
 
'author' => 'Bill Smith',
 
'dated'  => '2010-SEP-15'
);
echo
'<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
$array = array_prefix_keys("content_",$array1,$array2);
$array1 = $array[0];
$array2 = $array[1];
echo
'<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
?>

This will produce the following output:

Array
(
    [id] => 1
    [title] => about-us
    [author] => Bill Brown
    [dated] => 2009-SEP-15
)
Array
(
    [id] => 2
    [title] => about-them
    [author] => Bill Smith
    [dated] => 2010-SEP-15
)

Array
(
    [content_id] => 1
    [content_title] => about-us
    [content_author] => Bill Brown
    [content_dated] => 2009-SEP-15
)
Array
(
    [content_id] => 2
    [content_title] => about-them
    [content_author] => Bill Smith
    [content_dated] => 2010-SEP-15
)

Hope it helps!
Bill

[EDIT BY danbrown AT php DOT net: The original function and note was removed in favor of this update by the original author.  The original note also contained the following descriptive text.]

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster.

ethaizone at hotmail dot com (02-Sep-2009 03:34)

My English is weak but I want to share my code.
I want to change formation of array but when I use null is callback function in array_map().
It has problem in result so I write new small function for it.

<?php
function array_change_formation($arr=array()) {
   
$new_arr = array();
    foreach(
$arr as $k => $v)
        foreach(
$v as $k2 => $v2)
           
$new_arr[$k2][$k] = $v[$k2];
    return
$new_arr;
}
?>

Input:
Array
(
    [Human] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [Pet] => Array
        (
            [0] => Cat
            [1] => Dog
            [2] => Rabbit
            [3] => Rat
        )

)

OutPut:
Array
(
    [0] => Array
        (
            [Human] => 1
            [Pet] => Cat
        )

    [1] => Array
        (
            [Human] => 2
            [Pet] => Dog
        )

    [2] => Array
        (
            [Human] => 3
            [Pet] => Rabbit
        )

    [3] => Array
        (
            [Human] => 4
            [Pet] => Rat
        )

)

I hope it can useful.

galenjr at gmail dot com (15-Jun-2009 07:19)

Another way to array_map htmlentities with a specific quote style is to create a function that does it and map that function

<?php

function map_entities( $str ) {
    return
htmlentities( $str, ENT_QUOTES );
}
$good_array = array_map ( 'map_entities', $bad_array );

?>

radist-hack at yandex dot ru (01-Nov-2008 09:37)

To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a
= array(
  array(
1, 2, 3),
  array(
4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)

Heero (16-Oct-2008 06:02)

You can easily remove all HTML tags from $_GET or $_POST variables using something like this:

<?php

$_POST
= array_map('strip_tags', $_POST);
$_GET = array_map('strip_tags', $_GET);

?>

This is useful when you don't want to parse HTML.

stijnleenknegt at gmail dot com (23-Jul-2008 12:17)

If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array
= array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.

GUI (26-Jun-2008 03:48)

The following takes an array of objects, and returns the result of calling a member function on each object. So if I have an array of objects that all have a getName() method, calling array_map_objects("getName", $thingies) will return the array filled with the getName() value for each object.

<?php
function array_map_objects($member_function, $array) {
   
$values = array();

    if(
is_string($member_function) && is_array($array)) {
       
$callback = create_function('$e', 'return call_user_func(array($e, "' . $member_function .'"));');
       
$values = array_map($callback, $array);
    }

    return
$values;
}
?>

BloodElf (27-Apr-2008 02:32)

Here is a simple way to highlight the matched words in the search results:

<?php

function highlight($word) {
        static
$num = 1;
        return
'<span class="word' . $num++ . '">' . $word . '</span>';
}

$text = "ala bala nica turska panica";
$search = "bala turska";
$words = explode(' ', $search);

echo
str_replace($words, array_map("highlight", $words), $text);

moester at gmail dot com (02-Apr-2008 09:21)

Wish this was built in.  Mimics Ruby and Prototype's array pluck function.  Returns specific key/column from an array of objects.

<?php
function array_pluck($key, $array)
{
    if (
is_array($key) || !is_array($array)) return array();
   
$funct = create_function('$e', 'return is_array($e) && array_key_exists("'.$key.'",$e) ? $e["'. $key .'"] : null;');
    return
array_map($funct, $array);
}

// usage:

$a = array(array("id"=>10, "name"=>"joe"), array("id"=>11, "name"=>"bob"));

$ids = array_pluck("id", $a);        // == array(10,11)
$names = array_pluck("name", $a);    // == array("joe", "bob")

//works on non-keyed arrays also:

$a = array(array(3,4), array(5,6));
$col2 = array_pluck(1,$a);            // == array(4,6) (grab 2nd column of data)

?>

chreekat (12-Mar-2008 11:48)

I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this:

function callback($k, $v) { ... }

array_map( "callback", array_keys($array), $array);

jo at ho dot nl (17-Feb-2008 10:10)

Could also use things like...

array_keys(); and array_values(); offcourse...

However it's just an example off recursion via this function..
Which I found pretty handy at times dealing with arrays..

could also use:

<?php
call_user_func
(array($this, __FUNCTION), $args);
?>

or

<?php
call_user_fuc_array
(array($this, __FUNCTION__), $array);
?>

or

<?php
class{

   public function
__construct($arg){
       if(
is_array($arg)){
            new
self($arg);
       }
       else{
           echo
$arg.'<br/>'.PHP_EOL;
       }
   }
}
?>

Anyway.. plenty off examples..
It was just an idea for others...

avartabedian at webservice dot com dot uy (08-Feb-2008 01:39)

loaded67 at hotmail dot com, there is a little error in the add func params values.

Warning: Missing argument 2 for test::add(), called in /tmp/test.php on line 34 and defined in /tmp/test.php on line 6
Array => <br/>

now it runs...

<?php
class test{

   
//private $container = array();
  
   
final public function add($key, $value=NULL){
        
/* params values fix */
        
$value = $value==NULL?$key:$value;
        
/* recursion */
        
if(is_array($value)){
              
array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
        
/* procedural */
        
else{
             echo
$key.' => '.$value.'<br/>'.PHP_EOL;
            
// do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
        
}
    }
}
//
$array = array (
                              
'one'   => 'value1',
                              
'two'   => 'value2',
                              
'three' => 'value3'
                           
);

$t = new test;
$t->add($array);
?>

good luck!

loaded67 at hotmail dot com (08-Feb-2008 10:59)

this function is really nice for recursion in php!!!

example in a class:

<?php
class test{

   
//private $container = array();
   
   
final public function add($key, $value){
        
/* recursion */
        
if(is_array($value)){
              
array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
        
/* procedural */
        
else{
             echo
$key.' => '.$value.'<br/>'.PHP_EOL;
            
// do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
        
}
    }
}
//
$array = array (
                              
'one'   => 'value1',
                              
'two'   => 'value2',
                              
'three' => 'value3'
                           
);

$t = new test;
$t->add($array);
?>

you could easiely do this without a class too offcourse!
used in php 5.2.5

pmf (23-Jan-2008 03:02)

This function behaves exactly like array_map but additionally does not reject non-array arguments. Instead, it transforms them with the array_fill function to a constant valued array of required length according to the other array arguments (if any) and executes the original array_map function.

<?php

function array_map2() {
   
$args = func_get_args();

   
$callback = array_shift($args);
   
   
$args = array_map(
           
create_function('$a,$max','return is_array($a)? $a: array_fill(0,$max,$a);'),
           
$args,array_fill(0,count($args),array_reduce($args,
           
create_function('$v,$w','return max($v,is_array($w)? count($w): 1);'))));

   
array_unshift($args,$callback);
   
    return
call_user_func_array("array_map",$args);
}

?>

Example:

<?php

$get
= "first=value1&second=value2&third=value3";

print_r(array_map2("explode","=",explode("&",$get)));

?>

would print out:

<?php

Array
(
    [
0] => Array
        (
            [
0] => first
           
[1] => value1
       
)

    [
1] => Array
        (
            [
0] => second
           
[1] => value2
       
)

    [
2] => Array
        (
            [
0] => third
           
[1] => value3
       
)
)

?>

/pmf

henrique at webcoder dot com dot br (01-Nov-2007 04:02)

Adding method support to function by Andref (multidimensionalArrayMap).

function array_map_r( $func, $arr )
{
    $newArr = array();
   
    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }
       
    return $newArr;
}

array_map_r('function', array());
or
array_map_r(array('class', 'method'), array());

bturchik at iponweb dot net (19-Jul-2007 03:46)

Maybe this one will be useful for someone:

function array_map_helper($mapper, $array) {
    $mapper = preg_replace('/^return (.*?);$/', '$1', trim($mapper));
    $result = array();
    if (preg_match('/(\(?)(.*?)\s*=>\s*(.*?)(\)?)$/', $mapper, $matches)) {
        list($full_found, $array_open, $left, $right, $array_close) = $matches;
        if ($array_open && $array_close) {
            $mapper = '$result[] = array' . $full_found . ';';
        } else {
            $mapper = '$result[' . $left . '] = ' . $right . ';';
        }
    } else {
        $mapper = '$result[] = ' . $mapper . ';';
    }

    foreach ($array as $key => $value) {
        eval($mapper);
    }

    return $result;
}

should be used like:

$array = array(array('foo' => 11, 'bar' => 22),
               array('foo' => 111, 'bar' => 222),
               array('foo' => 1111, 'bar' => 2222));
$mapped = array_map_helper('$value["foo"] => $value["bar"]', $array);

var_dump will give

array(3) {
  [11]=>
  int(22)
  [111]=>
  int(222)
  [1111]=>
  int(2222)
}

or

$mapped = array_map_helper('$value["foo"]', $array);

var_dump will give

array(3) {
  [0]=>
  int(11)
  [1]=>
  int(111)
  [2]=>
  int(1111)
}

or

$mapped = array_map_helper('$value["foo"] + $value["bar"] . " at position $key"', $array);

var_dump will give

array(3) {
  [0]=>
  string(16) "33 at position 0"
  [1]=>
  string(17) "333 at position 1"
  [2]=>
  string(18) "3333 at position 2"
}

andref dot dias at pronus dot eng dot br (24-Oct-2006 08:14)

A recursive way to handle multidimensional arrays:

<?php

function multidimensionalArrayMap( $func, $arr )
    {
   
$newArr = array();
    foreach(
$arr as $key => $value )
        {
       
$newArr[ $key ] = ( is_array( $value ) ? multidimensionalArrayMap( $func, $value ) : $func( $value ) );
        }
    return
$newArr;
    }

?>

pcdinh at phpvietnam dot net (18-Mar-2006 04:50)

Hi benjaminhill,

You can apply a method of a instantiated class to array_maps as follows:

class Maths {
    function addOne($input) {
        return ($input + 1);
    }
}
$maths = new Maths();
$sum = array_map(array($maths, \\\'addOne\\\'), array(1, 2));
// where $maths is the object which has been instantiated before and addOne is its method without its own parameters
var_dump($sum);

The code fragment will return:

array
  0 => 2
  1 => 3

However, I love a syntax like this:

$sum = array_map($maths->addOne($this), array(1, 2));

where $this should be interpreted as each values extracted from the subsequent array, which in this case is array(1, 2).

This syntax reminds me of Javascript syntax.

PHP\\\'s callback mechanism should be improved.

(26-Aug-2005 02:57)

Here's a function, very helpfull to me, that allows you to map your callback on mixed args.

<?php
function array_smart_map($callback) {
   
// Initialization
   
$args = func_get_args() ;
   
array_shift($args) ; // suppressing the callback
   
$result = array() ;
   
   
// Validating parameters
   
foreach($args as $key => $arg)
        if(
is_array($arg)) {
           
// the first array found gives the size of mapping and the keys that will be used for the resulting array
           
if(!isset($size)) {
               
$keys = array_keys($arg) ;
               
$size = count($arg) ;
           
// the others arrays must have the same dimension
           
} elseif(count($arg) != $size) {
                return
FALSE ;
            }
           
// all keys are suppressed
           
$args[$key] = array_values($arg) ;
        }
   
   
// doing the callback thing
   
if(!isset($size))
       
// if no arrays were found, returns the result of the callback in an array
       
$result[] = call_user_func_array($callback, $args) ;
    else
        for(
$i=0; $i<$size; $i++) {
           
$column = array() ;
            foreach(
$args as $arg)
               
$column[] = ( is_array($arg) ? $arg[$i] : $arg ) ;
           
$result[$keys[$i]] = call_user_func_array($callback, $column) ;
        }
           
    return
$result ;
   
}
?>

Trying with :

<?php
// $_GET is ?foo=bar1-bar2-bar3&bar=foo1
print_r(array_smart_map('explode', '-', $_GET)) ;
?>

Returns :

array(
    [foo] => array(
        0 => bar1
        1 => bar2
        2 => bar3
    )

    [bar] => array(
        1 => foo1
    )
)

david dot tulloh at infaze dot com dot au (07-Jul-2005 12:53)

You can pass values to array_map by reference, essentially allowing you to use it as you would array_walk with multiple arrays as parameters.

A trivial example:
<?php
$a
= array(1,2,3,4,5);
$add_func = create_function('&$x, $y', '$x+=$y;');
array_map($add_func, $a, $a);
print_r($a);
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Vinicius Cubas Brand (23-Mar-2005 01:31)

The following function does exaclty the same thing of array_map. However, maintains the same index of the input arrays

<?php
   
function array_map_keys($param1,$param2,$param3=NULL)
    {
       
$res = array();

        if (
$param3 !== NULL)
        {
            foreach(array(
2,3) as $p_name)
            {
                if (!
is_array(${'param'.$p_name}))
                {
                   
trigger_error(__FUNCTION__.'(): Argument #'.$p_name.' should be an array',E_USER_WARNING);
                    return;
                }
            }
            foreach(
$param2 as $key => $val)
            {
               
$res[$key] = call_user_func($param1,$param2[$key],$param3[$key]);
            }
        }
        else
        {
            if (!
is_array($param2))
            {
               
trigger_error(__FUNCTION__.'(): Argument #2 should be an array',E_USER_WARNING);
                return;
            }
            foreach(
$param2 as $key => $val)
            {
               
$res[$key] = call_user_func($param1,$param2[$key]);
            }
        }
        return
$res;
    }
?>

For instance:

<?php
    $arr1
= array(
       
'3' => 'a',
       
'4' => 'b',
       
'5' => 'c'
       
);

   
$arr2 = array(
       
'3' => 'd',
       
'4' => 'e',
       
'5' => 'f'
       
);

   
$arr3 = array_map_keys(create_function('$a,$b','return $a.$b;'),$arr1,$arr2);

   
print_r($arr3);

?>

The result will be:

Array
(
    [3] => ad
    [4] => be
    [5] => cf
)

endofyourself at yahoo dot com (20-Feb-2005 07:29)

If you need to call a static method from array_map, this will NOT work:

<?PHP
array_map
('myclass::myMethod' , $value);
?>

Instead, you need to do this:

<?PHP
array_map
( array('myclass','myMethod') , $value);
?>

It is helpful to remember that this will work with any PHP function which expects a callback argument.

nd0 at gmx dot de (02-Jul-2004 12:42)

array_map works also fine with create_function:

<?php
$a
= array(1, 2, 3, 4, 5);
$b = array_map(create_function('$n', 'return $n*$n*$n;'), $a);
print_r($b);
?>

if you want to manipulate the elements of the array, instead to on a copy,
than take a look at array_walk:

<?php
$a
= array(1, 2, 3, 4, 5);
array_walk($a, create_function('&$n', '$n = $n*$n*$n;'));
print_r($a);
?>

The Result of both is:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

bishop (10-Apr-2004 01:07)

Occasionally, you may find that you need to pull out a column (or several) from an array.  Here's a map-like function to do that:

<?php
function &array_shear(&$arrays, $idx1 /* ... */) {
   
$indexes = func_get_args();
   
array_shift($indexes);

   
$newArrays = array ();

    foreach (
array_keys($arrays) as $arrayKey) {
       
$newArray = array ();
        foreach (
$indexes as $index) {
           
$newArray[$index] = $arrays[$arrayKey][$index];
            unset(
$arrays[$arrayKey][$index]);
        }
       
$newArrays[$arrayKey] = $newArray;
    }

    return
$newArrays;
}
?>

So, doing this:

<?php
$t1
= array (
         
2 => array ('a', 'b', 'c'),
         
1 => array ('d', 'e', 'f'),
         
5 => array ('g', 'h', 'i'),
      );

$t2 = array_shear($t1, 1, 0);

?>

will result in:

<?php

$t1
= array (
 
2 =>   array (    2 => 'c',  ),
 
1 =>   array (    2 => 'f',  ),
 
5 =>   array (    2 => 'i',  ),
);

$t2 = array (
 
2 =>   array (    1 => 'b',    0 => 'a',  ),
 
1 =>   array (    1 => 'e',    0 => 'd',  ),
 
5 =>   array (    1 => 'h',    0 => 'g',  ),
);

?>

stephen at mu dot com dot au (07-Jan-2003 06:02)

A note when doing something allong the lines of:

<?php
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.

dan at mojavelinux dot com (15-Jun-2002 06: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)

<?php
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!