PHP offers a variety of built-in functions to handle arrays, including the ability to reverse them. This article will explain how to reverse an array in PHP and demonstrate how to combine it with formatted text output for clearer presentation.
You can reverse an array using PHP's array_reverse() function. This function returns a new array with the elements in reverse order. For example:
$originalArray = [1, 2, 3, 4, 5];
$reversedArray = array_reverse($originalArray);
print_r($reversedArray); // Output: [5, 4, 3, 2, 1]
To format text output, you can use the printf() or sprintf() functions. These functions allow you to customize the output format and insert variables via placeholders, controlling alignment and display style. For example:
$name = "John Doe";
printf("Welcome, %s!\n", $name); // Output: Welcome, John Doe!
Combining the above, let's write a small script that reverses a list of words and outputs each word in uppercase:
$wordList = ["hello", "world", "from", "PHP"];
// Reverse the word list
$reversedList = array_reverse($wordList);
// Format and output the reversed word list
printf("Reversed word list:\n");
foreach ($reversedList as $word) {
printf("- %s\n", strtoupper($word));
}
When you run this script, it outputs:
Reversed word list:
- PHP
- FROM
- WORLD
- HELLO
This guide shows how to easily reverse arrays and output formatted text in PHP. Mastering these techniques can help you handle data processing and presentation more effectively.