find the shortest word in a string in php

You can find the shortest word in a string by using the explode() function to convert the string into an array of words, and then loop through the array to find the shortest word using strlen() function.

Here's an example code:

main.php
function findShortestWord($str) {
  $words = explode(" ", $str);
  $shortest_word = $words[0];

  foreach ($words as $word) {
    if (strlen($word) < strlen($shortest_word)) {
      $shortest_word = $word;
    }
  }

  return $shortest_word;
}

// Example usage
$shortest = findShortestWord("The quick brown fox jumps over the lazy dog");
echo "Shortest word: " . $shortest; // Output: "Shortest word: The"
407 chars
17 lines

In the example above, the findShortestWord() function takes a string argument $str and returns the shortest word in the string. The explode() function is used to split the string into an array of words, which is then looped through to find the shortest word. The strlen() function is used to determine the length of each word in the array. The if statement inside the loop checks if the length of the current word is less than the length of the current shortest word, and if so, sets the current word as the new shortest word. After the loop completes, the function returns the shortest word.

related categories

gistlibby LogSnag