PHP Examples

PHP Program - Reverse a given String



In PHP, the reverse of a given string can be found out by using below mentioned methods.

Method 1: Using iteration

In the example below, the string called MyString is reversed using ReverseString() function. Two variables l and r are created which initially points to first and last character of the string. If l is less than r, then the characters of MyString at indices l and r swapped. After swapping, l is increased by one and r is decreased by one until they cross each other. Finally, MyString will contain the reversed value of the initial string.

<?php
function ReverseString($MyString) {
  $l = 0;
  $r = strlen($MyString) - 1;

  while($r > $l){
    //swapping characters at indices l and r
    $c = $MyString[$l];
    $MyString[$l] = $MyString[$r];
    $MyString[$r] = $c;
    
    $l++;
    $r--;
  }
  echo "$MyString \n";
}

ReverseString("Hello World");
ReverseString("Programming is fun");
ReverseString("Reverse this string");
?>

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 2: Using Recursion

The above result can also be achieved using recursive function. Consider the example below:

<?php

function ReverseString($MyString) {
  if(($MyString == null) || (strlen($MyString) <= 1)) {
    echo ($MyString);
  } else {
    echo ($MyString[strlen($MyString) - 1]);
    ReverseString(substr($MyString, 0, 
                  (strlen($MyString) - 1)));
  }
}

ReverseString("Hello World");
echo "\n";

ReverseString("Programming is fun");
echo "\n";

ReverseString("Reverse this string");
echo "\n";
?>

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 3: Printing the string in reverse order

The same can be achieved by printing the string in reverse order. Consider the example below:

<?php
function ReverseString($MyString) {
  $last = strlen($MyString) - 1;

  for($i = $last; $i >= 0; $i--) {
    echo $MyString[$i];
  }
  echo "\n";
}

ReverseString("Hello World");
ReverseString("Programming is fun");
ReverseString("Reverse this string");
?>

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 4: Using built-in function - strrev()

The PHP built-in function strrev() can also be used to reverse a string. Consider the example below:

<?php
echo strrev("Hello World")."\n";
echo strrev("Programming is fun")."\n";
echo strrev("Reverse this string")."\n";
?>

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR