Reversing a String in PHP

Reversing a string is a common programming task. While PHP provides the built-in strrev() function, here’s an example of reversing a string without using this default function.

PHP Example:

Print Reverse of String by php program.
<?php
// Given string
$string = "TECHNICALGUIDE";

// Calculate the length of the string
$length = strlen($string);

// Initialize an empty string for the reversed output
$reversedString = "";

// Loop through the string in reverse order
for ($i = $length - 1; $i >= 0; $i--) {
    // Concatenate each character to the reversed string
    $reversedString .= $string[$i];
}

// Print the reversed string
echo $reversedString;
?>

EDIUGLACINHCET

Explanation:

  1. Given String: The string “TECHNICALGUIDE” is provided.
  2. String Reversal:
    • The length of the string is calculated using strlen().
    • An empty string ($reversedString) is initialized to store the reversed output.
    • The for loop iterates through the string in reverse order.
    • Each character is concatenated to the reversedString.
  3. Print Output: The reversed string “EDIUGLACINHCET” is printed.