Using PHP array_map() Function: Syntax, Parameters, and Practical Examples

This article explains the PHP array_map() function, its signature and parameters, and demonstrates how to use it with both named and anonymous callbacks to transform arrays, such as converting strings to uppercase and doubling numeric values.

php Courses
php Courses
php Courses
Using PHP array_map() Function: Syntax, Parameters, and Practical Examples

The array_map() function applies a user‑defined callback to each element of one or more arrays and returns a new array containing the transformed values.

Function signature

array_map ( callable $callback , array $array1 [, array $... ] ) : array

Parameter description

$callback

: The callback function that processes each element; it can be a named function or an anonymous function. $array1: The primary array to be processed. $...: Optional additional arrays whose elements are passed to the callback.

Return value: A new array composed of the elements returned by the callback.

Example 1 – Using a named function

The following code defines a function convert_to_uppercase() that converts a string to uppercase, then uses array_map() to apply it to an array of names.

<?php
function convert_to_uppercase($value) {
    return strtoupper($value);
}

$names = array("john", "james", "jane", "julie");
$names_uppercase = array_map("convert_to_uppercase", $names);

print_r($names_uppercase);
?>

The script prints:

Array
(
    [0] => JOHN
    [1] => JAMES
    [2] => JANE
    [3] => JULIE
)

Example 2 – Using an anonymous function

This example shows how to double each number in an array by passing an anonymous function to array_map().

<?php
$numbers = array(1, 2, 3, 4, 5);
$doubled_numbers = array_map(function($value) {
    return $value * 2;
}, $numbers);

print_r($doubled_numbers);
?>

The output is:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

In real‑world development, array_map() is frequently used for array transformations, filtering, or any operation where each element needs to be processed by a custom callback.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialcallbackarray_map
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.