Django Johnson
Django Johnson

Reputation: 1449

Check if multi-word string in if statement

How can I check if a string is a multi word sentence or just a single word?

I tried by splitting by a space so if it is one word, there will be only one word in the array and if there is more, then they will all be in the array.

But, when I try to split by a space and run through that array, I am getting no output.

Here is the code:

$input = "the quick brown fox jumped over the lazy dog";

$sentence = explode(" ", $input);

foreach($sentence as $item){
    echo $item;
}

The above is giving me no output.

So, I have 2 questions:

  1. How can I detect if a string is composed of multiple words in an if statement?
  2. Why isn't my above code splitting the sentence into an array with the words?

Upvotes: 1

Views: 2592

Answers (6)

AlexP
AlexP

Reputation: 9857

For reference there is also str_word_count($string) which will also provide the number of words within a string.

Upvotes: 2

Mike Purcell
Mike Purcell

Reputation: 19999

Haven't run the metrics between this or hek2mgl's solution, but this should be faster:

if (stripos($input, ' ') !== false) { echo 'ZOMG I HAS WORDS'; }

Also, as mentioned in the comments, the code you posted works as expected.

Upvotes: 5

hek2mgl
hek2mgl

Reputation: 158250

How can I detect if a string is composed of multiple words in an if statement?

if(count(explode(' ', $str)) > 0) { echo 'sentence'; }

Why isn't my above code splitting the sentence into an array with the words?

The code should work. I got (after adding a newline to the echo):

the
quick
brown
fox
jumped
over
the
lazy
dog

Upvotes: 1

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5438

Your code should be working fine in order to check if there is more than one word you need to check like below

$input = "the quick brown fox jumped over the lazy dog";

$sentence = explode(" ", $input);

echo "<pre>";
var_dump($sentence);
echo "</pre>";


if(count($sentence)){
echo "we have more than one word!";
}

Upvotes: 0

NolanPower
NolanPower

Reputation: 409

Heres some pseudocode for it:

String input = "The quick brown fox jumped over the lazy dog"

Array[] words = String.split(input,' ');
if(words.length > 1)

print " more than 1 word"

else

print "1 word"

Upvotes: -1

dremme
dremme

Reputation: 769

To check if there are spaces you can use a regex like:

$spaces = preg_match('/ /',$input);

This should return a 1 or 0 depending on if there is a space.

if( $spaces == 1 )
  // there is more than one word
else
  // there is only one word with no spaces

Your code looks error free other than that.

Upvotes: -1

Related Questions