0
0
PHPprogramming~5 mins

Array map function in PHP

Choose your learning style9 modes available
Introduction

The array map function helps you change every item in a list quickly. It makes a new list with the changed items.

You want to add 1 to every number in a list of scores.
You need to make all words in a list uppercase.
You want to get the length of each string in a list of names.
You want to convert a list of prices from dollars to euros.
You want to add a prefix to every item in a list of file names.
Syntax
PHP
<?php
function callback_function($item) {
    // change $item and return it
    return $item;
}

$new_array = array_map('callback_function', $original_array);
?>

The callback function is called for each item in the original array.

array_map returns a new array with the changed items, original stays the same.

Examples
Add 1 to each number in the list.
PHP
<?php
$numbers = [1, 2, 3];
$new_numbers = array_map(fn($num) => $num + 1, $numbers);
print_r($new_numbers);
Make all words uppercase using a built-in function.
PHP
<?php
$words = ['apple', 'banana', 'cherry'];
$upper_words = array_map('strtoupper', $words);
print_r($upper_words);
What if the array is empty? Result is also empty.
PHP
<?php
$empty = [];
$result = array_map(fn($x) => $x * 2, $empty);
print_r($result);
Works with one item too.
PHP
<?php
$single = [10];
$doubled = array_map(fn($x) => $x * 2, $single);
print_r($doubled);
Sample Program

This program shows how to use array_map to convert a list of prices from dollars to euros. It prints the original list and the converted list.

PHP
<?php
// Original array of prices in dollars
$prices_in_dollars = [10, 20, 30, 40];

// Function to convert dollars to euros (assume 1 dollar = 0.9 euros)
function convert_to_euros($price_in_dollars) {
    return $price_in_dollars * 0.9;
}

// Print original prices
echo "Original prices in dollars:\n";
print_r($prices_in_dollars);

// Use array_map to convert all prices
$prices_in_euros = array_map('convert_to_euros', $prices_in_dollars);

// Print converted prices
echo "Prices converted to euros:\n";
print_r($prices_in_euros);
?>
OutputSuccess
Important Notes

Time complexity is O(n) because it changes each item once.

Space complexity is O(n) because it makes a new array of the same size.

Common mistake: forgetting to return the changed item in the callback function.

Use array_map when you want to change every item in a list and keep the same order and size.

Summary

array_map applies a function to every item in an array and returns a new array.

The original array stays the same.

Works with empty arrays and arrays with one item too.