Php array map callback

array_map

array_map() returns an array containing the results of applying the callback to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback. The number of parameters that the callback function accepts should match the number of arrays passed to array_map() . Excess input arrays are ignored. An ArgumentCountError is thrown if an insufficient number of arguments is provided.

Parameters

A callable to run for each element in each array.

null can be passed as a value to callback to perform a zip operation on multiple arrays. If only array is provided, array_map() will return the input array.

An array to run through the callback function.

Supplementary variable list of array arguments to run through the callback function.

Return Values

Returns an array containing the results of applying the callback function to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback.

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Changelog

Version Description
8.0.0 If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING .

Examples

Example #1 array_map() example

Читайте также:  Адаптивные единицы измерения css

$a = [ 1 , 2 , 3 , 4 , 5 ];
$b = array_map ( ‘cube’ , $a );
print_r ( $b );
?>

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

Example #2 array_map() using a lambda function

$func = function( int $value ): int return $value * 2 ;
>;

print_r ( array_map ( $func , range ( 1 , 5 )));

print_r ( array_map ( fn ( $value ): int => $value * 2 , range ( 1 , 5 )));

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

Example #3 array_map() — using more arrays

function show_Spanish ( int $n , string $m ): string
return «The number < $n >is called < $m >in Spanish» ;
>

function map_Spanish ( int $n , string $m ): array
return [ $n => $m ];
>

$a = [ 1 , 2 , 3 , 4 , 5 ];
$b = [ ‘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 );
?>

The above example will output:

// 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, shorter ones will be extended with empty elements to match the length of the longest.

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 #4 Performing a zip operation of arrays

$a = [ 1 , 2 , 3 , 4 , 5 ];
$b = [ ‘one’ , ‘two’ , ‘three’ , ‘four’ , ‘five’ ];
$c = [ ‘uno’ , ‘dos’ , ‘tres’ , ‘cuatro’ , ‘cinco’ ];

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

The above example will output:

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 ) )

Example #5 null callback with only array

The above example will output:

array(3) < [0]=>int(1) [1]=> int(2) [2]=> int(3) >

Example #6 array_map() — with string keys

$arr = [ ‘stringkey’ => ‘value’ ];
function cb1 ( $a ) return [ $a ];
>
function cb2 ( $a , $b ) return [ $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 ));
?>

The above example will output:

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" > >

Example #7 array_map() — associative arrays

While array_map() does not directly support using the array key as an input, that may be simulated using array_keys() .

$arr = [
‘v1’ => ‘First release’ ,
‘v2’ => ‘Second release’ ,
‘v3’ => ‘Third release’ ,
];

// Note: Before 7.4.0, use the longer syntax for anonymous functions instead.
$callback = fn ( string $k , string $v ): string => » $k was the $v » ;

$result = array_map ( $callback , array_keys ( $arr ), array_values ( $arr ));

The above example will output:

array(3) < [0]=>string(24) "v1 was the First release" [1]=> string(25) "v2 was the Second release" [2]=> string(24) "v3 was the Third release" >

See Also

  • array_filter() — Filters elements of an array using a callback function
  • array_reduce() — Iteratively reduce the array to a single value using a callback function
  • array_walk() — Apply a user supplied function to every member of an array
  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    array_map

    Функция array_map() возвращает массив, содержащий элементы array1 после их обработки callback -функцией. Количество параметров, передаваемых callback -функции, должно совпадать с количеством массивов, переданным функции array_map() .

    Список параметров

    Callback-функция, применяемая к каждому элементу в каждом массиве.

    Массив, к которому применяется callback -функция.

    Дополнительные массивы для обработки callback -функцией.

    Возвращаемые значения

    Возвращает массив, содержащий все элементы array1 после применения callback -функции к каждому из них.

    Примеры

    Пример #1 Пример использования array_map()

    $a = array( 1 , 2 , 3 , 4 , 5 );
    $b = array_map ( «cube» , $a );
    print_r ( $b );
    ?>

    В результате переменная $b будет содержать:

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

    Пример #2 Использование array_map() вместе с lambda-функцией (начиная с версии PHP 5.3.0)

    print_r ( array_map ( $func , range ( 1 , 5 )));
    ?>

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

    Пример #3 Пример использования array_map() : обработка нескольких массивов

    function show_Spanish ( $n , $m )
    return( «Число $n по-испански — $m » );
    >

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

    $a = array( 1 , 2 , 3 , 4 , 5 );
    $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 );
    ?>

    Результат выполнения данного примера:

    // вывод $c Array ( [0] => Число 1 по-испански - uno [1] => Число 2 по-испански - dos [2] => Число 3 по-испански - tres [3] => Число 4 по-испански - cuatro [4] => Число 5 по-испански - cinco ) // вывод $d Array ( [0] => Array ( [1] => uno ) [1] => Array ( [2] => dos ) [2] => Array ( [3] => tres ) [3] => Array ( [4] => cuatro ) [4] => Array ( [5] => cinco ) )

    Обычно при обработке двух или более массивов, они имеют одинаковую длину, так как callback-функция применяется параллельно к соответствующим элементам массивов. Если массивы имеют различную длину, более короткие из них дополняется элементами с пустыми значениями до длины самого длинного массива.

    Интересным эффектом при использовании этой функции является создание массива массивов, что может быть достигнуто путем использования значения NULL в качестве имени callback-функции.

    Пример #4 Создание массива массивов

    $a = array( 1 , 2 , 3 , 4 , 5 );
    $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 ) )

    Если массив-аргумент содержит строковые ключи, то результирующий массив будет содержать строковые ключи тогда и только тогда, если передан ровно один массив. Если передано больше одного аргумента, то результирующий массив будет всегда содержать числовые ключи.

    Пример #5 Использование array_map() со строковыми ключами

    $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" > >

    Смотрите также

    • array_filter() — Фильтрует элементы массива с помощью callback-функции
    • array_reduce() — Итеративно уменьшает массив к единственному значению, используя callback-функцию
    • array_walk() — Применяет заданную пользователем функцию к каждому элементу массива
    • информация о типе callback

    Источник

    How to Use the array_map Function in PHP With Examples

    Sajal Soni

    Sajal Soni Last updated Apr 16, 2021

    In this quick article, we’ll discuss the array_map function in PHP. Basically, we’ll go through the syntax of the array_map function and demonstrate how to use it with real-world examples.

    The array_map function allows you to apply a callback function to transform elements of an array. It’s really useful when you want to perform a specific operation on every element of an array. Apart from that, it also allows you to combine multiple arrays into a single multidimensional array.

    Instead of iterating through all the array elements with the foreach construct to perform a specific operation on them, you should prefer the array_map function, which is built specifically for this.

    Syntax of the array_map Function

    In this section, we’ll go through the syntax of the array_map function to understand how it works.

    Let’s have a look at the syntax of the array_map function:

    array_map ( callable|null $callback , array $array , array . $arrays ) : array 

    The first argument is the callback function, which is called when the array_map function iterates over the elements of an array. It could be a user-defined function or a class method in the callable form.

    The second argument is the source array on which the callback function will run.

    In most cases, you would only need these two arguments. But the array_map function allows you to pass additional array arguments that are passed as arguments to the callback function. They will all be combined into one multi-dimensional array in the output. It’s interesting that you can pass null as the callback, and array_map just performs a zip operation on the source arrays. I’ll demonstrate this with a couple of real-world examples in the next section.

    The array_map function returns an array of all values processed by the callback function.

    In the next section, we’ll go through a couple of real-world examples to understand how the array_map function works.

    Real-World Examples

    In this section, we’ll discuss how to use the array_map function in different ways.

    How to Lowercase an Array

    This is one of the most basic and useful examples. When you want to perform a specific operation on all the elements of an array, the array_map function is the way to go!

    function lowercase($element) 

    Источник

Оцените статью