Current Location: Home> Latest Articles> Practical Methods to Find the Third Smallest Value in a PHP Array

Practical Methods to Find the Third Smallest Value in a PHP Array

gitbox 2025-08-04

What Is the Third Smallest Value in an Array

In PHP, an array is a data type that can store multiple values. If you have an array, you might want to find the third smallest value, which is the value that ranks third when all elements are sorted in ascending order.

Implementation Methods

Method One: Sort and Select the Third Element

You can sort the array first, then directly select the third element from the sorted array.

$arr = array(3, 5, 2, 8, 1);
sort($arr);
echo $arr[2]; // Outputs 2

Method Two: Remove Duplicates, Sort, and Select Third Element

If the array contains duplicate elements, you can use array_unique() to remove duplicates, then sort the array and pick the third element.

$arr = array(3, 5, 2, 8, 1, 2, 3, 5);
$arr = array_unique($arr);
sort($arr);
echo $arr[2]; // Outputs 3

Method Three: Slice Part of the Array, Sort, and Select Third Element

Use array_slice() to get a part of the array, then sort that portion and pick the third element.

$arr = array(3, 5, 2, 8, 1);
$arr = array_slice($arr, 0, 3);
sort($arr);
echo $arr[2]; // Outputs 3

Method Four: Custom Function with Loop to Find Third Smallest

You can define a custom function that uses nested loops to sort the array partially and find the third smallest value.


function third_smallest($arr)
{
    $n = count($arr);
    $temp = 0;
    for ($i = 0; $i < $n; $i++) {
        for ($j = $i + 1; $j < $n; $j++) {
            if ($arr[$j] < $arr[$i]) {
                $temp = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j] = $temp;
            }
        }
        if ($i == 2) {
            break;
        }
    }
    return $arr[2];
}
$arr = array(3, 5, 2, 8, 1);
echo third_smallest($arr); // Outputs 3

Summary

All these methods can effectively find the third smallest value in an array. Sorting and directly accessing the element is simple and efficient. Removing duplicates before sorting is suitable for arrays with repeated values. Custom functions provide more control over the sorting process. Choose the method that best fits your specific needs to handle array data effectively.