Skip to content
Advertisement

get every words backwards using php

I want to get the text and print every words backwards.

Example: Hello World

Output: World hello

This is my codes so far. It is different, I get output backwards but per string.

$string = "hello world";  

$length = strlen($string);  
for ($i=($length-1) ; $i >= 0 ; $i--)   
{  
  echo $string[$i];  
}  

OUTPUT of the above code is

dlrow olleh

Please help me guys. Thank you.

Advertisement

Answer

Another way to do it with array_reverse(),

<?php
$str = 'Hello World';
$strArray = explode(" ", $str);       
$strArray = array_reverse($strArray);       
$str = implode($strArray, " ");
echo $str;
?>

DEMO: https://3v4l.org/ZfEqQ

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement