PHP Program to Reverse String with Example
You can reverse a string in PHP using the built-in function
strrev(), for example: $reversed = strrev($string);.Examples
Inputhello
Outputolleh
InputPHP
OutputPHP
Input
Output
How to Think About It
To reverse a string, think of reading the characters from the end to the start. PHP provides a simple function
strrev() that does this by taking the input string and returning a new string with characters in reverse order.Algorithm
1
Get the input string.2
Use the built-in function to reverse the string.3
Return or print the reversed string.Code
php
<?php
$string = "hello";
$reversed = strrev($string);
echo $reversed;
?>Output
olleh
Dry Run
Let's trace the string "hello" through the code.
1
Input string
$string = "hello"
2
Reverse string
$reversed = strrev("hello"); // returns "olleh"
3
Output result
echo "olleh"
| Step | Value of string | Value of reversed |
|---|---|---|
| 1 | hello | |
| 2 | hello | olleh |
| 3 | hello | olleh |
Why This Works
Step 1: Using strrev()
The strrev() function takes a string and returns a new string with characters in reverse order.
Step 2: Assign reversed string
We store the reversed string in a variable to use or print later.
Step 3: Print the result
Using echo outputs the reversed string to the screen.
Alternative Approaches
Manual loop reversal
php
<?php $string = "hello"; $reversed = ""; for ($i = strlen($string) - 1; $i >= 0; $i--) { $reversed .= $string[$i]; } echo $reversed; ?>
This method manually builds the reversed string by looping backward; it is more verbose but helps understand the process.
Using array functions
php
<?php $string = "hello"; $array = str_split($string); $reversedArray = array_reverse($array); $reversed = implode('', $reversedArray); echo $reversed; ?>
This method converts the string to an array, reverses it, then joins it back; useful for learning array manipulation.
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each character once, so time grows linearly with string length.
Space Complexity
A new string is created to hold the reversed characters, so space also grows linearly.
Which Approach is Fastest?
Using strrev() is fastest and simplest; manual loops or array methods are slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| strrev() | O(n) | O(n) | Quick and simple reversal |
| Manual loop | O(n) | O(n) | Learning how reversal works |
| Array functions | O(n) | O(n) | Practicing array manipulation |
Use
strrev() for a quick and efficient way to reverse strings in PHP.Beginners often try to reverse strings by looping forward or mixing up indexes, leading to incorrect results.