Skip to content
PHP Logo

How can you modify an array before it is output in PHP?

To modify an array before it is output in PHP, you can use array functions such as array_map or array_walk to apply a callback function to each element of the array and make the necessary modifications. This allows you to manipulate the array data before displaying it to the user.

php
// Sample array
$numbers = [1, 2, 3, 4, 5];

// Modify the array by squaring each element
$modifiedNumbers = array_map(function($num) {
    return $num * $num;
}, $numbers);

// Output the modified array
print_r($modifiedNumbers);