Open Laboratory for Technocrats

Grab the developer role, learn concepts & prepare with senior software engineers to get solutions for problems in a software job. Coding and Programming Solutions crafted for you.

PHP - reverseWords from String - Solution


We need to write code in PHP where the Input will be passed to us in String and we have to reverse the order of the words.
Example:
Input- I am Developer
Output- Developer am I
Problem Statement:
Write a function reverseWords() that takes a message as a string and reverses the order of the words in place

A solution in PHP:
function reverseWords($message)
{
    return implode(' ', array_reverse( str_word_count( $message, 1)));
}

In the above solution, we have taken simple inbuilt functions of PHP.

str_word_count - It returns information about words used in a string, when using with the second param as 1 we will get an array containing all the words found inside the input string.
array_reverse - It returns an array with elements in reverse order
implode - It joins array elements with a string 

Keep Coding and Keep Smiling :) 

Top #3 Articles