Skip to content
Advertisement

Reverse a string in php without using any string function

In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().

Uninitialized string offset: -1 in D:xampphtdocsPhpProject1index.php on line xx

$string = "ZEESHAN";

$i =0;

while(($string[$i])!=null){

        $i++;

}

$i--;

while(($string[$i])!=null){

        echo $string[$i];

$i--;

}

Advertisement

Answer

$string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){ 
      $reverse = $string[$i].$reverse; 
      $i++;
}
echo $reverse;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement