Php array map functions

PHP array_map() Function

Send each value of an array to a function, multiply each value by itself, and return an array with the new values:

Definition and Usage

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

Tip: You can assign one array to the function, or as many as you like.

Syntax

Parameter Values

Parameter Description
myfunction Required. The name of the user-made function, or null
array1 Required. Specifies an array
array2 Optional. Specifies an array
array3 Optional. Specifies an array

Technical Details

Return Value: Returns an array containing the values of array1, after applying the user-made function to each one
PHP Version: 4.0.6+

More Examples

Example

Using a user-made function to change the values of an array:

Example

Example

Change all letters of the array values to uppercase:

$a=array(«Animal» => «horse», «Type» => «mammal»);
print_r(array_map(«myfunction»,$a));
?>

Example

Assign null as the function name:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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

Источник

PHP array_map

Summary: in this tutorial, you will learn how to use the PHP array_map() function that creates a new array whose elements are the results of applying a callback to each element.

Introduction to the PHP array_map() function

Suppose that you have an array that holds the lengths of squares:

 $lengths = [10, 20, 30];Code language: HTML, XML (xml)

To calculate the areas of the squares, you may come up with the foreach loop like this:

 $lengths = [10, 20, 30]; // calculate areas $areas = []; foreach ($lengths as $length) < $areas[] = $length * $length; >print_r($areas);Code language: HTML, XML (xml)
Array ( [0] => 100 [1] => 400 [2] => 900 )Code language: PHP (php)

The foreach iterates over the elements of the $lengths array, calculates the area of each square and adds the result to the $areas array.

Alternatively, you can use the array_map() function that achieves the same result:

 $lengths = [10, 20, 30]; // calculate areas $areas = array_map(function ($length) < return $length * $length; >, $lengths); print_r($areas);Code language: HTML, XML (xml)

In this example, the array_map() applies an anonymous function to each element of the $lengths array. It returns a new array whose elements are the results of the anonymous function.

From PHP 7.4, you can use an arrow function instead of an anonymous function like this:

 $lengths = [10, 20, 30]; // calculate areas $areas = array_map( fn ($length) => $length * $length, $lengths ); print_r($areas);Code language: HTML, XML (xml)

PHP array_map() function syntax

The following shows the array_map() function syntax:

array_map ( callable|null $callback , array $array , array . $arrays ) : arrayCode language: PHP (php)

The array_map() has the following parameters:

  • $callback – a callable to apply to each element in each array.
  • $array – is an array of elements to which the callback function applies.
  • $arrays – is a variable list of array arguments to which the callback function applies.

The array_map() function returns a new array whose elements are the result of the callback function.

This tutorial focuses on the following form of the array_map() function:

array_map ( callable $callback , array $array ) : arrayCode language: PHP (php)

PHP array_map() function examples

Let’s take some more examples of using the array_map() function.

1) Using the PHP array_map() with an array of objects

The following defines a class that has three properites: $id , $username , and $email and a list of User objects:

 class User < public $id; public $username; public $email; public function __construct(int $id, string $username, string $email) < $this->id = $id; $this->username = $username; $this->email = $email; > > $users = [ new User(1, 'joe', 'joe@phptutorial.net'), new User(2, 'john', 'john@phptutorial.net'), new User(3, 'jane', 'jane@phptutorial.net'), ];Code language: HTML, XML (xml)

The following illustrates how to use the array_map() function to get a list of usernames from the the $users array:

 class User < public $id; public $username; public $email; public function __construct(int $id, string $username, string $email) < $this->id = $id; $this->username = $username; $this->email = $email; > > $users = [ new User(1, 'joe', 'joe@phptutorial.net'), new User(2, 'john', 'john@phptutorial.net'), new User(3, 'jane', 'jane@phptutorial.net'), ]; $usernames = array_map( fn ($user) => $user->username, $users ); print_r($usernames); Code language: HTML, XML (xml)
Array ( [0] => joe [1] => john [2] => jane )Code language: PHP (php)

2) Using a static method as a callback

The callback function argument of the array_map() can be a public method of a class. For example:

 class Square < public static function area($length) < return $length * $length; > > $lengths = [10, 20, 30]; $areas = array_map('Square::area', $lengths); print_r($areas);Code language: HTML, XML (xml)
  • First, define the Square class that has the area() public static method.
  • Second, create an array that holds the lengths of the three squares.
  • Third, calculate areas of the squares based on the lengths in the $lengths array using the static method Square::area .

Note that the syntax for passing a public static method to the array_map() function is as follows:

'className::staticMethodName'Code language: JavaScript (javascript)

And the public static method must accept the array element as an argument.

Summary

  • Use the PHP array_map() method to create a new array by applying a callback function to every element of another array.

Источник

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) 

Источник

Читайте также:  Вывод количества страниц php
Оцените статью