-1

How do I reverse the sentence using the code below

Input Hello World

Output World Hello

using this code

while ($line = trim(fgets(STDIN))) { 
   //$line contains the line of the input
   echo $line . "\n";
}

2 Answers2

3

explode() followed by array_reverse() followed by implode()

$string = 'hello world i like php';
$string = implode(' ',array_reverse(explode(' ',$string)));
echo $string; // php like i world hello
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
0

Method 1:

<?php
$str = "Hello World";
$i = 0;
while( $d = $str[$i] )
{
     if( $d == " "){

        $out = " ".$temp.$out;
        $temp = "";
    }else{
        $temp.=$d;

    }
    $i++;
}
echo $temp.$out; 
?>

Method 2:

$s = "Hello World";
// break the string up into words
$words = explode(' ',$s);
// reverse the array of words
$words = array_reverse($words);
// rebuild the string
$s = join(' ',$words);
print $s;

Method 3:

$reversed_s = join(' ',array_reverse(explode(' ',$s)));
kzhao14
  • 2,470
  • 14
  • 21