Pages

Thursday, August 18, 2016

PHP: Reverse words

This program is going to read sentences from an archive and then reverse the order of the sentence written on it. Create an archive called input.txt where you will write different sentences and a PHP file index.php were you will write the following code:


<?php
$fh = fopen("input.txt", "r");
while (!feof($fh)) {
 
$test = trim(fgets($fh));
 echo (nl2br(reversed($test) . "\n"));
     if (empty($test) == true) {
            break;      
    }
}
function reversed($test) {

$words = explode(" ", $test);
$reversed = array_reverse($words);
return $testResult = implode(" ", $reversed);
}
fclose($fh);
?>

The above code is going to give you the following results:

Input
Hello world!

Output
world! Hello


0 Comments:

Post a Comment