- array_map
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- Use Associative Array Keys in array_map: 3 PHP Code Examples
- Using Associative Array Keys in PHP array_map
- Multiple arrays usage – A review
- Associative Array Keys array_map() PHP Code Example
- PHP arrays associative keys in PHP array_map function
- Using Associative Array Keys in PHP array_map
- Want to explore more useful PHP tutorials?
- PHP array_map() Function
- Example 1: How to Use PHP array_map() function
- Example 2: Creating an array of arrays using array_map()
- Example 3: PHP array_map() Using Multiple Arrays
- Example 4: PHP array_map() with string keys
- Example 5: PHP array_map() using a lambda function
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 » );
>
?php
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» );
?php
$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 ));
?>?php
Результат выполнения данного примера:
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
Use Associative Array Keys in array_map: 3 PHP Code Examples
It is impossible to get the array keys in the php array_map function. A good workaround if you need the keys is to use the array_keys function and pass it as an additional array into the array_map function.
Using Associative Array Keys in PHP array_map
We have already seen the PHP array_map and some important related caveats.
In a nutshell, the array_map function applies a callback to every element of the given arrays.
One essential quirk of the function is that it passes the values of the given arrays to the callback function. There is no inherent way to pass a key as a parameter to the callback function.
This article will show how to use associative array keys in PHP array_map function.
To get the most out of this article, we recommend reading our article about array_map PHP.
Multiple arrays usage – A review
Let’s review the array_map function when it gets more than one array as an argument. This review is crucial because we will use two arrays to use associative keys in the array_map function.
The example gets two arrays; one consists of Roman numerals, and the other has equivalent numbers in English. It uses array_map to get the corresponding values from both arrays simultaneously.
Associative Array Keys array_map() PHP Code Example
"The Roman Numeral is in English", $roman_numerals, $english_numbers)); /* OUTPUT Array ( [0] => The Roman Numeral I is One in English [1] => The Roman Numeral II is Two in English [2] => The Roman Numeral III is Three in English [3] => The Roman Numeral IV is Four in English [4] => The Roman Numeral V is Five in English ) */ ?>
Both these arrays were equal, and the array_map PHP function mapped them using the values from both the arrays.
But, what if the two arrays were unequal?
Luckily, the function is robust enough to handle them. It pads the shorter array with null values. The following example demonstrates it.
"The Roman Numeral is in English", $roman_numerals, $english_numbers)); /* OUTPUT Array ( [0] => The Roman Numeral I is One in English [1] => The Roman Numeral II is Two in English [2] => The Roman Numeral III is Three in English [3] => The Roman Numeral IV is Four in English [4] => The Roman Numeral V is Five in English [5] => The Roman Numeral VI is in English ) */ ?>
The array_map assigns a null value to the missing sixth element of the second array, $english_numbers.
PHP arrays associative keys in PHP array_map function
So, after a quick review of passing multiple arrays arguments to the array_map function, we will extend this idea to pass array keys to the callback function.
Since the callback function doesn’t fetch the key, we have to find a workaround.
The idea is to pass the keys as a separate array to the PHP array_map. PHP has a function for separating keys into an array of its own, the array_keys function.
So, let’s move on to the example and try out this idea.
"Javascript", "Edward" => "Java", "Rey" => "Python", "Sanjay" => "PHP", "Ali" => "C++", "Sarah" => "C#", "Bob" => "Android" ]; $dev_names = array_keys($developers); $resultant = array_map(function($name, $tech) < return "is a developer"; >, $dev_names, $developers); print_r($resultant); /* OUTPUT Array ( [0] => Anna is a Javascript developer [1] => Edward is a Java developer [2] => Rey is a Python developer [3] => Sanjay is a PHP developer [4] => Ali is a C++ developer [5] => Sarah is a C# developer [6] => Bob is a Android developer ) */ ?>
The idea works like a charm.
We had a $developers array with their names as keys and skills as values. So, the array_keys isolate the names into a separate array, $dev_names.
The array_map function gets $dev_names, and $developers arrays as arguments, just as we saw in the review section. The callback can fetch the values from both these arrays.
This idea is a neat workaround to overcome the inherent limitation of the array_map function.
Using Associative Array Keys in PHP array_map
In this article, we have seen how to use associative array keys in PHP array_map function. The article reviews the use of multiple arrays as arguments in the array_map, followed by the main tutorial of using arrays associative keys in array_map PHP.
The example uses the array_keys function to get the array of keys.
Finally, the keys array and the actual array are passed as arguments to the function. Hopefully, this article has been helpful. Stay tuned for more interesting articles and tutorials related to PHP.
Want to explore more useful PHP tutorials?
We have many fun articles related to PHP. You can explore these to learn more about PHP.
PHP array_map() Function
It returns an array containing the values of array1 after applying the user-made function to each one.
Example 1: How to Use PHP array_map() function
function square($x) return($x * $x); > $arrA = array(19, 21, 46, 29); $arrO = array_map("square",$arrA); print_r($arrO);
We have defined one array and then passed that array to the array_map function, and that function returns the square of all the array’s items and forms a new array with that value.
Example 2: Creating an array of arrays using array_map()
$arrA = array(19, 21, 46, 29); $arrB = array('K', 'K', 'A', 'V'); $arrO = array_map(null, $arrA, $arrB); print_r($arrO);
Example 3: PHP array_map() Using Multiple Arrays
function subtractAdd($a, $b, $c) return $a - $b + $c; > $arrA = array(19, 21, 46, 29); $arrB = array(18, 19, 20, 21); $arrC = array(1, 2, 26, 8); $arrO = array_map("subtractAdd", $arrA, $arrB, $arrC); print_r($arrO);
Example 4: PHP array_map() with string keys
function stormBreaker($a) return $a."***".$a; > $arrA = ["name" => "Krunal", "age" => 26 ]; $arrO = array_map("stormBreaker", $arrA); print_r($arrO);
Example 5: PHP array_map() using a lambda function
$func = function($value) return $value * 2; >; print_r(array_map($func, range(1, 5)));
We have used the $func as a lambda function and range() function to provide the value between 1 to 5.