Write a PHP program to reverse a string without using the strrev() function

Reversing a string is a common string manipulation task in PHP programming. It means arranging the characters of a string in the opposite order. In this program, we reverse a string without using PHP is built-in strrev() function.

PHP Program: Reverse a String Without Using strrev()
Program:

<?php

$str = "Hello World";
$reverse = "";

for ($i = strlen($str) - 1; $i >= 0; $i--) {
  $reverse .= $str[$i];
}

echo "Original String: " . $str . "<br>";
echo "Reversed String: " . $reverse;

?>

Output

Original String: Hello World
Reversed String: dlroW olleH

Explanation

First, we declare a variable named $str and assign the value "Hello World" to it. Next, we initialize an empty string variable named $reverse, which will store the reversed string.

We then use a for loop to traverse the original string from the last character to the first character. The strlen() function calculates the length of the string. Since string indexes start from zero, we begin at strlen($str) - 1.

Inside the loop, $str[$i] accesses the character at the current index. The concatenation assignment operator (.=) adds that character to the $reverse variable. The loop continues until the index becomes less than zero.

Finally, the echo statement displays both the original string and the reversed string.

For example, "Hello World" becomes "dlroW olleH". This program helps beginners understand string indexing, loops, and string concatenation. It works with ordinary English text in PHP 7.4 and PHP 8.x.

12 Views