Current Location: Home> Function Categories> array_map

array_map

Apply a callback function for each element of the array
Name:array_map
Category:Array
Programming Language:php
One-line Description:Send each value in the array to a user-defined function and return a new value.

Definition and usage

array_map() function applies the user-defined function to each value in the array and returns the array with the new value after the user-defined function is applied.

The number of parameters accepted by the callback function should be consistent with the number of arrays passed to array_map() function.

Tip: You can enter one or more arrays into the function.

Example

Example 1

Apply the function to each value in the array, multiplying each value by itself, and returning an array with the new value:

 <?php
function myfunction ( $v )
{
  return ( $v * $v ) ;
}

$a = array ( 1 , 2 , 3 , 4 , 5 ) ;
print_r ( array_map ( "myfunction" , $a ) ) ;
?>

Try it yourself

Example 2

Use user-defined functions to change the value of an array:

 <?php
function myfunction ( $v )
{
if ( $v === "Dog" )
  {
  return "Fido" ;
  }
return $v ;
}

$a = array ( "Horse" , "Dog" , "Cat" ) ;
print_r ( array_map ( "myfunction" , $a ) ) ;
?>

Try it yourself

Example 3

Use two arrays:

 <?php
function myfunction ( $v1 , $v2 )
{
if ( $v1 === $v2 )
  {
  return "same" ;
  }
return "different" ;
}

$a1 = array ( "Horse" , "Dog" , "Cat" ) ;
$a2 = array ( "Cow" , "Dog" , "Rat" ) ;
print_r ( array_map ( "myfunction" , $a1 , $a2 ) ) ;
?>

Try it yourself

Example 4

Change all letters of the value in the array to capitalize:

 <?php
function myfunction ( $v )
{
$v = strtoupper ( $v ) ;
  return $v ;
}

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

Try it yourself

Example 5

When assigning the function name to null:

 <?php
$a1 = array ( "Dog" , "Cat" ) ;
$a2 = array ( "Puppy" , "Kitten" ) ;
print_r ( array_map ( null , $a1 , $a2 ) ) ;
?>

Try it yourself

grammar

 array_map ( myfunction , array1 , array2 , array3 ... )
parameter describe
myfunction Required. The name of the user-defined function, or null.
array1 Required. Specify array.
array2 Optional. Specify array.
array3 Optional. Specify array.
Similar Functions
Popular Articles