Map function to array php

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 .
Читайте также:  METANIT.COM

Examples

Example #1 array_map() example

$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

    Источник

    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.

    Источник

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