In this PHP tutorial, you shall learn how to loop through words in a given string using explode() function and For loop, with example programs.

PHP – Iterate over words in String

To loop through words in a string in PHP, use explode() function with space as delimiter. The explode() functions returns an array containing words and you can then use a looping statement to traverse through the words one by one.

Step by step process

The following is a step by step process to split string into words.

  1. Take a string with words.
  2. Define the delimiter. Usually, space would be delimiter between words in a string.
  3. Call explode() function, with the delimiter and string passed as arguments.
  4. explode() returns an array containing words. Save it to a variable.
  5. Use foreach statement to loop through each item in the array.

Example

In this example, we will take a string containing words, explode it with a specific delimiter, collect the words into a variable, and print them in a foreach statement.

PHP Program

</>
Copy
<?php
$str = "Apple is healthy.";
$delimiter = ' ';
$words = explode($delimiter, $str);

foreach ($words as $word) {
    echo $word;
    echo "<br>";
}
?>

Program Output

PHP - Iterate over words in String

As an improvisation, you can clean the words from punctuation marks. Also, you may convert the string to a lower case, so that the words would be uniform with respect to case.

Conclusion

In this PHP Tutorial, we learned how to loop through words in a string, using explode() function and foreach statement.