Find Minimum Value of an Array in PHP

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

Finding the minimum in an unsorted array is a single left-to-right scan: start with $arr[0], then update whenever a smaller value appears. This tutorial covers the pattern, empty-array handling, negatives, a live preview, worked PHP examples, edge cases, and complexity.

Definition

Smallest value

Return the smallest element in an array of numbers.

Linear Scan

One pass

Track a running minimum while walking the array.

Init Rule

$arr[0] first

Seed $minVal with the first element, then compare the rest.

Empty Guard

No min

Reject empty arrays before scanning.

Live Preview

Sample → 2

Run the classic sample array in the browser.

O(n) Cost

O(1) space

One pass, constant extra memory — faster than sorting.

Introduction

Finding the minimum in an unsorted array means returning the smallest value. Start with the first element as the current minimum; whenever you see a smaller number, update it.

After one pass, the running minimum is the answer. The same idea works for all-negative arrays — the minimum is simply the most negative value.

Why it matters?

It is a classic interview warm-up that tests loops, comparisons, and empty-input thinking — and it mirrors finding the maximum.

Key Highlights

Running Min

Update whenever $x < $minVal.

Seed With First

Avoid sentinel values that break negatives.

Empty Guard

Raise or validate before indexing.

Beat Sorting

Do not sort when you only need the min.

In short: if the array is non-empty, set $minVal = $arr[0], then for each later value update when smaller.

📝 Problem & Approach

Given a non-empty array of integers, return the smallest value using one linear scan.

php
// [12, 5, 7, 3, 2, 8, 10] -> 2
// $minVal starts at 12, then updates to 5, 3, 2

Inputs & Outputs

ItemTypeDescription
$arrarrayNon-empty array of numbers.
Return / printint / textThe smallest value in the array.

Minimal workflow

Pseudocode
function findMin(arr):
    if arr is empty:
        error
    min_val <- arr[0]
    for each value in arr from second element:
        if value < min_val:
            min_val <- value
    return min_val

Method comparison

MethodIdeaNotes
Linear scanRunning minimumInterview default — O(n), O(1) space
Built-in minmin($arr)Fine in apps; show loops in interviews
Sort then take firstSort ascendingSlower — avoid when only min is needed

⚡ Quick Reference

GoalPattern
Seed$minVal = $arr[0]
Updateif ($arr[$i] < $minVal) { $minVal = $arr[$i]; }
Empty guardif (count($arr) === 0) throw new InvalidArgumentException(...)
Slice loopforeach (array_slice($arr, 1) as $x)
Track indexKeep $minI when updating
Built-inmin($arr) (after explaining the scan)

📋 Scan vs min() vs Sort

Same answer — different costs and interview signals.

Linear scan
running min

This page — clear O(n) interview style

Built-in
min($arr)

Production shortcut after you can explain it

Sort
sort($copy); $copy[0]

Overkill — usually O(n log n)

Interview tip
mention empty

Define behavior for [] up front

Context

When This Problem Shows Up

Reach for a running minimum whenever you need the smallest value in one pass.

  1. Interview warm-ups

    Loops, comparisons, and empty-array discussion.

  2. After maximum

    Same pattern; previous page used the opposite comparison.

  3. Scores and readings

    Lowest score, coldest temperature, cheapest price.

  4. Teaching comparisons

    Practice less-than updates and negatives.

  5. Not for sorting needs

    If you need order of all elements, sort instead.

Key benefit: one short loop that locks in running state, empty guards, and O(n) reasoning.

🔮 Live Preview

Uses the same sample array as Example 1: 12, 5, 7, 3, 2, 8, 10.

Runs the same linear-scan logic in JavaScript.

Live result
Press “Find minimum”.

Examples Gallery

Three complete PHP programs — classic scan to 2, all-negative array, and min-with-index tracking. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and a mixed positive sample.

Example 1 — Find Minimum (Reference Program)

A reusable helper function and a sample array with answer 2.

php
<?php
function findMin(array $arr): int
{
    if (count($arr) === 0) {
        throw new InvalidArgumentException("Array must contain at least one element.");
    }

    $minVal = $arr[0];
    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] < $minVal) {
            $minVal = $arr[$i];
        }
    }
    return $minVal;
}

$array = [12, 5, 7, 3, 2, 8, 10];
$minValue = findMin($array);
echo "Minimum value in the array: " . $minValue . PHP_EOL;
?>

How It Works

The function raises a clear error for empty input and uses one simple pass for normal arrays. Running min starts at 12, then updates to 5, 3, and finally 2.

⚡ Negatives Still Work

The minimum is the smallest value — even when every element is negative.

Example 2 — When Every Element Is Negative

The same algorithm still works; minimum is the most negative value.

php
<?php
function findMin(array $arr): int
{
    if (count($arr) === 0) {
        throw new InvalidArgumentException("Array must contain at least one element.");
    }

    $minVal = $arr[0];
    foreach (array_slice($arr, 1) as $x) {
        if ($x < $minVal) {
            $minVal = $x;
        }
    }
    return $minVal;
}

$negatives = [-9, -3, -1, -7];
echo "Minimum (most negative): " . findMin($negatives) . PHP_EOL;
?>

How It Works

Seeding with $arr[0] (not zero) is essential — initializing to 0 would wrongly beat every negative. Here -9 is smaller than -3, -1, and -7.

⚙️ Track Position Too

Common follow-up: return both the minimum and its first index.

Example 3 — Minimum With Index

Updates both value and index whenever a strictly smaller element appears.

php
<?php
function findMinWithIndex(array $arr): array
{
    if (count($arr) === 0) {
        throw new InvalidArgumentException("Array must contain at least one element.");
    }

    $minVal = $arr[0];
    $minI = 0;
    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] < $minVal) {
            $minVal = $arr[$i];
            $minI = $i;
        }
    }
    return [$minVal, $minI];
}

$array = [12, 5, 7, 3, 2, 8, 10];
[$value, $index] = findMinWithIndex($array);
echo "Minimum $value found at index $index" . PHP_EOL;
?>

How It Works

Strict < keeps the first occurrence if duplicates exist. Use <= only if you intentionally want the last index of the minimum.

🧠 How the Algorithm Finds the Min

1

Guard empty

If the array is empty, raise an error — no minimum exists.

Safety
2

Seed $minVal

Set $minVal = $arr[0] as the first candidate.

Init
3

Scan and update

For each later element, replace $minVal when smaller.

Loop
=

Minimum ready

Return the final running minimum.

🔎 Worked Walkthrough — Sample Array

Trace the running minimum for [12, 5, 7, 3, 2, 8, 10].

StepSee$minVal
Start1212
Next55
Next75 (unchanged)
Next33
Next22
Next82 (unchanged)
Next102 (unchanged)

Final answer: 2 — matching Example 1.

Use Cases

Where finding an array minimum shows up beyond the interview prompt.

1. Interview Warm-Ups

One-pass loops and empty-array talk.

Example: write findMin($arr).

2. After Maximum

Same scan; previous page used >.

Example: swap > for <.

3. Scores & Lows

Lowest score or coldest reading in a series.

Example: min temperature today.

4. Negatives Practice

Show why seeding with $arr[0] beats using 0.

Example: min of [-9, -1].

5. Complexity Talk

State O(n) vs sorting for interviews.

Example: n-1 comparisons lower bound.

6. Index Follow-Ups

Return position of the minimum too.

Example: Example 3 pattern.

Pro Tip: open with “empty check, seed $arr[0], one pass with <” before writing code.

Advantages

Why the linear-scan approach works well in interviews.

  1. 1. Optimal Simple Cost

    O(n) time and O(1) extra space for unsorted input.

  2. 2. Easy to Trace

    Dry-run a short array and watch $minVal update.

  3. 3. Handles Negatives

    Seeding with $arr[0] works for all-negative arrays.

  4. 4. Easy to Extend

    Track index, or flip to maximum with one change.

Pro Tip: lead with the manual scan; mention min($arr) only as a production aside.

Usage Tips

Small habits that keep min-finding solutions interview-ready.

  1. 1. Guard Empty First

    Raise before reading $arr[0].

  2. 2. Seed With $arr[0]

    Do not initialize to 0 when negatives are possible.

  3. 3. Prefer Strict <

    Keeps the first index if you also track position.

  4. 4. Skip Sorting

    Sorting is slower when you only need the min.

  5. 5. State O(n) / O(1)

    One pass, constant extra memory.

Pro Tip: dry-run 12 → 5 → 3 → 2 aloud — if that matches, your update logic is correct.

Common Pitfalls

Mistakes that commonly break min-finding solutions.

  1. 1. Empty Array Crash

    Reading $arr[0] when the array is empty.

    → Guard with count($arr) === 0 first.

  2. 2. Initializing to Zero

    Using $minVal = 0 on all-positive arrays can wrongly keep 0.

    → Seed with $arr[0] instead.

  3. 3. Sorting Unnecessarily

    Sorting just to take the first element.

    → Use one O(n) scan.

  4. 4. Off-by-One Loop

    Starting the loop at 0 and comparing $arr[0] to itself only.

    → Loop from index 1 (or use array_slice($arr, 1)).

  5. 5. Wrong Comparison for Max

    Copying min code but forgetting to flip < to >.

    → Maximum uses the opposite comparison.

Edge Cases

Handle these before claiming the scan is complete.

Empty

Empty array

No minimum exists; handle this before scanning.

Single

One element

That element is automatically the minimum.

Negatives

All negative

Minimum is the most negative value (e.g. -9).

Dupes

Repeated minimum

Value is unchanged; index depends on < vs <=.

Mixed

Positives and negatives

Same scan — no special case needed.

Floats

Non-integers

Same comparison logic works for floats.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Lower bound. Unsorted min needs at least n-1 comparisons in the worst case.
  • Idempotent on dups. Multiple copies of the min do not change the returned value.
  • Symmetric twin. Maximum uses the same pass with > instead of <.
  • Online-friendly. You can update the min as new values arrive without storing all of them.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run the sample

  • Trace [12, 5, 7, 3, 2, 8, 10]
  • Expect final min 2

2. All negatives

  • Reproduce Example 2
  • Confirm answer -9

3. Empty guard

  • Call findMin([])
  • Assert InvalidArgumentException (or your chosen policy)

4. Min with index

  • Implement Example 3
  • Decide first vs last on ties

Notes

  • Algorithm: running minimum in one pass.
  • Cost: O(n) time, O(1) extra space.
  • Important edge: define behavior for empty array.
  • PHP has min($arr), but interviewers often ask for the manual scan first. Huge data can combine partial minima in parallel.

Quick Takeaway: guard empty, seed with $arr[0], update on <, return in O(n) time.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single scanO(n)O(1)
Built-in minO(n)O(1)
Sort then take firstO(n log n)depends on sort

For unsorted input, a single scan is the standard interview answer.

Wrap Up

🎉 Conclusion

Finding the minimum is a one-pass running minimum: guard empty arrays, seed with $arr[0], and update on smaller values. The same pattern works for negatives and extends cleanly to tracking the index.

Practice the three examples above, then continue to the multiplication table tutorial.

Empty check first, then $minVal = $arr[0], update when $x < $minVal.

💡 Best Practices

✅ Do

  • Guard empty arrays first
  • Seed with $arr[0]
  • Use one O(n) scan
  • Mention negatives and duplicates
  • State O(n) time / O(1) space

❌ Don’t

  • Index empty arrays
  • Initialize min to 0 blindly
  • Sort just to find the min
  • Skip the empty-array discussion
  • Forget that -9 < -1

Key Takeaways

Knowledge Unlocked

Five things to remember about array minimum

Find the smallest value the interview-friendly way.

5
Core concepts
0 02

Seed

Start at $arr[0]

Init
! 03

Empty

Guard first

Safety
04

Negatives

Still works

Edge
O 05

Cost

O(n) / O(1)

Analysis

❓ Frequently Asked Questions

It picks the first element as the initial candidate, then every later element gets compared against it.
There is no minimum value for an empty array. Handle this case explicitly with an error or validation.
Yes. The minimum is still the smallest value, even if every element is negative (for example -9 is smaller than -1).
The algorithm still returns that minimum value. Duplicates do not change the answer.
No. Sorting is usually slower than a single scan when you only need the minimum.
One pass over n elements: O(n) time and O(1) extra space.
It is fine in real code. Interviews often ask you to write the manual linear scan first so you show the comparison logic.
Same one-pass pattern; only the comparison flips from less-than to greater-than.

Did you Know? 🔊

Finding the smallest value in an unsorted list still takes a single left-to-right pass: O(n) time and O(1) extra memory. You cannot do better in the worst case without extra structure, because any unseen element could be the new minimum.

Continue to Multiplication Table

Learn how to print a multiplication table with nested loops and clean formatting.

Multiplication table tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful