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";
}
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";
}
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
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)));