Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_map()

Example

Pass each value of an array to a function to multiply each value by itself, and return an array with the resulting values.

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

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

Definition and Usage

The array_map() function passes each value of an array to a user-defined function and returns a new array with the values modified by that function.

 

Tip: You can provide one array or multiple arrays to the function.

Syntax

array_map(myfunction, array1, array2, array3, …)

Parameter Values

Parameter

Description

myfunction

Required. The name of the user-defined function or null.

array1

Required. Specifies an array.

array2

Optional. Specifies an additional array.

array3

Optional. Provides an array.

Technical Details

Return Value:

Returns an array with the values from array1, each modified by applying the user-defined function.

PHP Version:

4.0.6+

More Examples

Example

Using a user-defined function to modify the values 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));
?>

Example

Using 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));
?>

Example

Convert all letters in the array values to uppercase:

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

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

Example

Set the function name to null:

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