Home > Backend Development > PHP Tutorial > Reverse array and output formatted text using PHP

Reverse array and output formatted text using PHP

王林
Release: 2024-04-28 21:24:02
Original
615 people have browsed it

To reverse a PHP array and format the text, you can use the following steps: Use the array_reverse() function to reverse the order of the array elements. Use the printf() or sprintf() function to specify the output format and alignment, and to insert variables. Put the reversed array into the printf() or sprintf() function, format it and output it.

Reverse array and output formatted text using PHP

Reverse an array in PHP and output formatted text

There are a series of built-in functions available in PHP that can be used to easily handle arrays, including reverse they. This article will explore how to reverse an array using PHP and demonstrate how to use it with formatted text through a practical example.

Reverse Array

To reverse a PHP array, you can use the array_reverse() function. This function will rearrange the elements in the array in reverse order and return a new array. For example:

$originalArray = [1, 2, 3, 4, 5];
$reversedArray = array_reverse($originalArray);

print_r($reversedArray); // 输出: [5, 4, 3, 2, 1]
Copy after login

Format text

To format text, you can use the printf() or sprintf() function. These functions allow you to control the format and alignment of the output and include placeholders for inserting variables. For example:

$name = "John Doe";
printf("欢迎, %s!\n", $name); // 输出: 欢迎, John Doe!
Copy after login

Practical example: Reverse and convert a word list to uppercase

Let's combine this and create a small script that reverses and converts a word list to uppercase.

$wordList = ["hello", "world", "from", "PHP"];

// 反转单词列表
$reversedList = array_reverse($wordList);

// 格式化并输出反转的单词列表
printf("反转后的单词列表:\n");
foreach ($reversedList as $word) {
    printf("- %s\n", strtoupper($word));
}
Copy after login

This script will reverse the list of words and output them item by item in uppercase:

反转后的单词列表:
- PHP
- FROM
- WORLD
- HELLO
Copy after login

The above is the detailed content of Reverse array and output formatted text using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template