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

How to reverse string and array in php

青灯夜游
青灯夜游Original
2022-06-10 20:29:081873browse

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);
?>

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)

##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);
?>
Description
Required. Specifies an array.
Optional. Specifies whether to retain the original array key names. Possible values:

true
  • false

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!

Statement:
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