Definition
Smallest value
Return the smallest element in an array of numbers.
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.
Smallest value
Return the smallest element in an array of numbers.
One pass
Track a running minimum while walking the array.
$arr[0] first
Seed $minVal with the first element, then compare the rest.
No min
Reject empty arrays before scanning.
Sample → 2
Run the classic sample array in the browser.
O(1) space
One pass, constant extra memory — faster than sorting.
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.
It is a classic interview warm-up that tests loops, comparisons, and empty-input thinking — and it mirrors finding the maximum.
Update whenever $x < $minVal.
Avoid sentinel values that break negatives.
Raise or validate before indexing.
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.
Given a non-empty array of integers, return the smallest value using one linear scan.
// [12, 5, 7, 3, 2, 8, 10] -> 2
// $minVal starts at 12, then updates to 5, 3, 2 | Item | Type | Description |
|---|---|---|
$arr | array | Non-empty array of numbers. |
| Return / print | int / text | The smallest value in the array. |
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 | Idea | Notes |
|---|---|---|
| Linear scan | Running minimum | Interview default — O(n), O(1) space |
Built-in min | min($arr) | Fine in apps; show loops in interviews |
| Sort then take first | Sort ascending | Slower — avoid when only min is needed |
| Goal | Pattern |
|---|---|
| Seed | $minVal = $arr[0] |
| Update | if ($arr[$i] < $minVal) { $minVal = $arr[$i]; } |
| Empty guard | if (count($arr) === 0) throw new InvalidArgumentException(...) |
| Slice loop | foreach (array_slice($arr, 1) as $x) |
| Track index | Keep $minI when updating |
| Built-in | min($arr) (after explaining the scan) |
Same answer — different costs and interview signals.
running minThis page — clear O(n) interview style
min($arr)Production shortcut after you can explain it
sort($copy); $copy[0]Overkill — usually O(n log n)
mention emptyDefine behavior for [] up front
Reach for a running minimum whenever you need the smallest value in one pass.
Loops, comparisons, and empty-array discussion.
Same pattern; previous page used the opposite comparison.
Lowest score, coldest temperature, cheapest price.
Practice less-than updates and negatives.
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.
Uses the same sample array as Example 1: 12, 5, 7, 3, 2, 8, 10.
Three complete PHP programs — classic scan to 2, all-negative array, and min-with-index tracking. Click View Output to reveal sample console results.
A reusable helper and a mixed positive sample.
A reusable helper function and a sample array with answer 2.
<?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;
?> 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.
The minimum is the smallest value — even when every element is negative.
The same algorithm still works; minimum is the most negative value.
<?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;
?> 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.
Common follow-up: return both the minimum and its first index.
Updates both value and index whenever a strictly smaller element appears.
<?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;
?> Strict < keeps the first occurrence if duplicates exist. Use <= only if you intentionally want the last index of the minimum.
If the array is empty, raise an error — no minimum exists.
Set $minVal = $arr[0] as the first candidate.
For each later element, replace $minVal when smaller.
Return the final running minimum.
Trace the running minimum for [12, 5, 7, 3, 2, 8, 10].
| Step | See | $minVal |
|---|---|---|
| Start | 12 | 12 |
| Next | 5 | 5 |
| Next | 7 | 5 (unchanged) |
| Next | 3 | 3 |
| Next | 2 | 2 |
| Next | 8 | 2 (unchanged) |
| Next | 10 | 2 (unchanged) |
Final answer: 2 — matching Example 1.
Where finding an array minimum shows up beyond the interview prompt.
One-pass loops and empty-array talk.
Example: write findMin($arr).
Same scan; previous page used >.
Example: swap > for <.
Lowest score or coldest reading in a series.
Example: min temperature today.
Show why seeding with $arr[0] beats using 0.
Example: min of [-9, -1].
State O(n) vs sorting for interviews.
Example: n-1 comparisons lower bound.
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.
Why the linear-scan approach works well in interviews.
O(n) time and O(1) extra space for unsorted input.
Dry-run a short array and watch $minVal update.
Seeding with $arr[0] works for all-negative arrays.
Track index, or flip to maximum with one change.
Pro Tip: lead with the manual scan; mention min($arr) only as a production aside.
Small habits that keep min-finding solutions interview-ready.
Raise before reading $arr[0].
Do not initialize to 0 when negatives are possible.
Keeps the first index if you also track position.
Sorting is slower when you only need the min.
One pass, constant extra memory.
Pro Tip: dry-run 12 → 5 → 3 → 2 aloud — if that matches, your update logic is correct.
Mistakes that commonly break min-finding solutions.
Reading $arr[0] when the array is empty.
→ Guard with count($arr) === 0 first.
Using $minVal = 0 on all-positive arrays can wrongly keep 0.
→ Seed with $arr[0] instead.
Sorting just to take the first element.
→ Use one O(n) scan.
Starting the loop at 0 and comparing $arr[0] to itself only.
→ Loop from index 1 (or use array_slice($arr, 1)).
Copying min code but forgetting to flip < to >.
→ Maximum uses the opposite comparison.
Handle these before claiming the scan is complete.
No minimum exists; handle this before scanning.
That element is automatically the minimum.
Minimum is the most negative value (e.g. -9).
Value is unchanged; index depends on < vs <=.
Same scan — no special case needed.
Same comparison logic works for floats.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
O(n) time, O(1) extra space.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.
| Approach | Time | Extra space |
|---|---|---|
| Single scan | O(n) | O(1) |
Built-in min | O(n) | O(1) |
| Sort then take first | O(n log n) | depends on sort |
For unsorted input, a single scan is the standard interview answer.
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.
$arr[0]Find the smallest value the interview-friendly way.
Running min
PatternStart at $arr[0]
InitGuard first
SafetyStill works
EdgeO(n) / O(1)
AnalysisFinding 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.
Learn how to print a multiplication table with nested loops and clean formatting.
8 people found this page helpful