find the kth smallest element in an array in php

To find the kth smallest element in an array, one approach is to sort the array first and then select the kth element. Here is a PHP implementation of this approach:

main.php
function findKthSmallest($arr, $k) {
  sort($arr);
  return $arr[$k-1];
}
74 chars
5 lines

The sort() function sorts the elements of the array in ascending order. We subtract 1 from the $k value to obtain the index of the kth smallest element in the sorted array.

Example usage:

main.php
$arr = [3, 1, 4, 2, 5];
$k = 3;
echo findKthSmallest($arr, $k); // output: 3
77 chars
4 lines

In this example, the 3rd smallest element in the array is 3.

gistlibby LogSnag