PHP program to find the minimum element in an array

To find the minimum element in an array in PHP, you can use a custom function or built−in functions. Here are different approaches to accomplish this task.

Using Custom Function

The manual approach involves iterating through the array and comparing each element ?

<?php
    function get_min_value($my_array){
        $n = count($my_array);
        $min_val = $my_array[0];
        for ($i = 1; $i < $n; $i++) {
            if ($min_val > $my_array[$i]) {
                $min_val = $my_array[$i];
            }
        }
        return $min_val;
    }
    
    $my_array = array(56, 78, 91, 44, 0, 11);
    echo "The lowest value of the array is " . get_min_value($my_array);
?>
The lowest value of the array is 0

Using min() Function

PHP provides a built−in min() function that directly returns the minimum value ?

<?php
    $my_array = array(56, 78, 91, 44, 0, 11);
    $min_value = min($my_array);
    echo "The minimum value is: " . $min_value;
?>
The minimum value is: 0

How It Works

The custom function get_min_value() works as follows:

  • Initialization: The first element $my_array[0] is set as the initial minimum value
  • Iteration: The loop starts from index 1 and compares each element with the current minimum
  • Comparison: If a smaller element is found, it becomes the new minimum value
  • Return: The function returns the final minimum value after checking all elements

Comparison

Method Performance Code Length Readability
Custom Function O(n) Longer Educational
min() Function O(n) Shorter Cleaner

Conclusion

While the custom approach helps understand the logic, using PHP's built−in min() function is more efficient and cleaner for production code. Both methods have the same time complexity.

Updated on: 2026-03-15T09:09:14+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements