Array Functions
Advertisements

PHP array_map() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_map() function applies a callback function to each element of an array and returns a new array with modified elements.

The following table summarizes the technical details of this function.

Return Value: Returns an array containing the results of applying the callback function to each element of array1 and other arrays (if provided).
Version: PHP 4.0.6+

Syntax

The basic syntax of the array_map() function is given with:

array_map(callback, array1, array2, ...);

The following example shows the array_map() function in action.

<?php
// Define callback function
function cube($n){
    return ($n * $n * $n);
}

// Sample array
$numbers = array(1, 2, 3, 4, 5);

// Applying callback function to each number
$result = array_map("cube", $numbers);
print_r($result);
?>

Note: The keys will be preserved in the returned array, if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.


Parameters

The array_map() function accepts the following parameters.

Parameter Description
callback Required. Specifies the callback function to run for each element in each array.
array Required. Specifies an array to work on.
... Optional. Specifies more array to work on.

More Examples

Here're some more examples showing how array_map() function actually works:

In the following example the resulting array will preserve the keys of the original array.

<?php
// Define callback function
function total($price){
    $tax = 5/100; // 5%
    return ($price *= (1 + $tax));
}

// Sample arrays
$products = array("bread"=>3, "tea"=>5, "coffee"=>10);

// Applying callback function to each element
$result = array_map("total", $products);
print_r($result);
?>

The following example demonstrates the passing of more than one array to this function.

<?php
// Define callback function
function phonics($v1, $v2){
    return "$v1 is for $v2";
}

// Sample arrays
$letters = array("a", "b", "c", "d");
$words = array("apple", "ball", "cat", "dog");

// Applying callback function to each element
$result = array_map("phonics", $letters, $words);
print_r($result);
?>

The following example demonstrates how to change the case of each string value of an array to uppercase using the PHP's built-in strtoupper() function:

<?php
// Sample arrays
$fruits = array("apple", "banana", "orange", "mango");

// Applying callback function to each element
$result = array_map("strtoupper", $fruits);
print_r($result);
?>

Tip: You are not limited only to custom functions with array_map(), you can also use PHP's built-in functions as we've used strtoupper() function in the above example.

Advertisements
Bootstrap UI Design Templates