find the kth longest word in a string in php

To find the kth longest word in a string in PHP, we can follow these steps:

  1. First, we need to convert the string into an array of words using the explode() function.
  2. Next, we can use the usort() function to sort the array of words by their length in descending order.
  3. Finally, we can return the kth element of the sorted array using the index k-1.

Here's the implementation:

main.php
function kthLongestWord($str, $k) {
  // convert string to array of words
  $words = explode(' ', $str);
  
  // sort the array by word length in descending order
  usort($words, function($a, $b) {
    return strlen($b) - strlen($a);
  });
  
  // return the kth longest word
  return $words[$k-1];
}

// Example usage
$str = "The quick brown fox jumps over the lazy dog";
$k = 3; // find the 3rd longest word
$result = kthLongestWord($str, $k);
echo "The $k" . "rd" . " longest word is: " . $result;
// Output: "The 3rd longest word is: jumps"
545 chars
20 lines

In this example, the function kthLongestWord() takes two arguments: $str is the input string, and $k is the desired rank of the longest word. The function returns the desired word as a string.

gistlibby LogSnag