Home > Backend Development > PHP Problem > How to reverse string and array in php

How to reverse string and array in php

青灯夜游
Release: 2023-03-16 11:04:02
Original
1990 people have browsed it

In PHP, you can use the strrev() and array_reverse() functions to achieve string reversal and array reversal. strrev() is used to reverse a string, the syntax is "strrev($string)". array_reverse() is used to reverse an array, the syntax is "array_reverse($array,$preserve)"; the parameter "$preserve" can be omitted, the default value is "false", if the value is set to TRUE, the numeric keys will be retained.

How to reverse string and array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php has two built-in functions. Implement string reversal and array reversal

  • ##strrev()

  • array_reverse()

strrev() function can reverse string

strrev($string) Function to reverse string$string .

  • Return value: Returns the reversed string.

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$str="Hello World!";
echo "原字符串:".$str."<br>";
echo "反转字符串:".strrev($str);
?>
Copy after login

How to reverse string and array in php

array_reverse() can achieve array reversal

The array_reverse() function can reverse an array, returning the array in reverse order. Syntax format:

array_reverse($array,$preserve)
Copy after login

##Parameter$array$preserveIf set to TRUE, numeric keys will be preserved. Non-numeric keys are not affected by this setting and will always be retained. ##Example: output original array, reverse Array, reverse array retaining the original array key name
<?php
header("Content-type:text/html;charset=utf-8");
$a=array("Volvo","XC90",array("BMW","Toyota"));
$reverse=array_reverse($a);
$preserve=array_reverse($a,true);
var_dump($a);
var_dump($reverse);
var_dump($preserve);
?>
Copy after login

Recommended learning: "How to reverse string and array in phpPHP Video Tutorial

"

The above is the detailed content of How to reverse string and array in 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
Description
Required. Specifies an array.
Optional. Specifies whether to retain the original array key names. Possible values:

true
  • false