find the longest word in a string in php

One way to find the longest word in a string in PHP is to convert the string into an array of words, loop through each word to determine its length, and keep track of the longest word found so far.

Here's an example implementation:

main.php
$string = "The quick brown fox jumps over the lazy dog.";

$words = explode(" ", $string); // convert string to array of words
$longest_word = "";

foreach ($words as $word) {
    if (strlen($word) > strlen($longest_word)) {
        $longest_word = $word;
    }
}

echo "The longest word is: " . $longest_word; // output: "The longest word is: jumps"
351 chars
13 lines

In this code, we first use the explode() function to convert the string into an array of words, splitting it at every space character. We then set an initial value of an empty string for the variable $longest_word.

Next, we loop through each word in the array using a foreach loop. For each word, we check if its length is greater than the length of the current $longest_word. If it is, we update the value of $longest_word to be the current word.

Once the loop has finished, we output the value of $longest_word to display the longest word in the original string.

gistlibby LogSnag