Reverse Each Word in the Sentence in JavaScript and PHP

Use Case: Showing competence in your programming interview

A question that you may be asked during a programming interview is "reverse a string" or "reverse a portion of a string". The reason why you might be asked this is because the interviewer wants to see your ability to manipulate strings.

In this post, I'm going to show you how to best answer this question in both JavaScript and PHP.

If you'd rather see this post in video format, watch the video below and be sure to subscribe to my YouTube playlist Tyler Answers Interview Questions.

JavaScript Solution

The best way to solve this dilemma in JavaScript is to create a reusable function that can be used to reverse strings given a specific separator.

In the answer below, we've created a function called rvsBy that takes a string and a separator value. We'll use this function to first reverse our entire sentence by character, and then undo the reversed order of words by calling the function on the reversed sentence.

JavaScript

const sentence = 'This is a sentence!'

const rvsBy = (string, separator) => {
	return string.split(separator).reverse().join(separator)
}

const newSentence = rvsBy(sentence, '') // !ecnetnes a si sihT
const answer =  rvsBy(newSentence, ' ') // sihT si a !ecnetnes

We've now answered the interview question by keeping the order of the sentence while reversing the individual words.

PHP Solution

In the PHP solution, we'll create the same basic function. There are some differences, however, due to how PHP allows us to manipulate strings and arrays.

Also, we'll have to perform a conditional statement to use str_split instead of explode when attempting to create a new array of individual characters.

Other than that, you'll see the function is overall the same.

PHP

$sentence = 'This is a sentence!';

function rvsBy($string, $separator) {
	if ($separator === '') {
		$array = str_split($string);
	} else {
		$array = explode($separator, $string);
	}
	$reversed = array_reverse($array);
	return join($separator, $reversed);
}

$reversedSentence = rvsBy($sentence, ''); // !ecnetnes a si sihT
$answer = rvsBy($reversedSentence, ' '); // sihT si a !ecnetnes

Tweet me @tylerewillis

Or send an email:

And support me on Patreon