PHP

Transform PHP Array Elements with a Callback Function

Discover how to use `array_map` to apply a transformation to every element in a PHP array, creating a new array with modified values.

<?php
$numbers = [1, 2, 3, 4, 5];

$squaredNumbers = array_map(function($number) {
    return $number * $number;
}, $numbers);

echo "Squared Numbers: ";
print_r($squaredNumbers);

$names = ['alice', 'bob', 'charlie'];

$capitalizedNames = array_map('ucfirst', $names);

echo "Capitalized Names: ";
print_r($capitalizedNames);
?>
How it works: The `array_map()` function applies a specified callback function to each element of the input arrays. It returns a new array containing all the elements after applying the callback function, making it ideal for transforming data, such as squaring numbers, formatting strings, or converting data types.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs