Find Maximum Value of an Array in PHP

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Arrays

What you’ll learn

  • The classic linear scan: keep a running maximum and update it whenever you see a larger element.
  • A reusable findMax function, count($array) for size, and clean PHP output with echo.
  • A second example with all negative values, plus a live preview for the reference array.

Overview

You walk the array once. The answer after visiting every slot is the largest value stored—no sorting required.

Two programs

Reference mix of positives and an all-negative demo.

Live preview

Same six numbers as example 1; prints the max in the page.

Interview hook

Mention O(n) time and the empty-array edge case when asked.

Prerequisites

for/foreach loops, arrays, and echo.

  • Basic PHP syntax and indexed arrays like $arr = [ ... ].
  • Understanding count($arr) to get array length.

The idea

Pick the first element as your provisional winner. For each next element, if it is greater than the current winner, replace the winner. After the last index, the winner is the maximum.

This is one pass, left to right—easy to code and easy to explain in an interview.

Live preview

Uses the same six integers as example 1: 14, 7, 25, 31, 10, 42.

Runs the same comparison logic in JavaScript.

Live result
Press “Find maximum”.

Algorithm

Goal: return the largest value among n integers in contiguous memory.

Validate length

Require size >= 1 (or handle empty arrays explicitly in production code).

Initialize

Set max = arr[0].

Scan

For i from 1 to size - 1, if arr[i] > max, set max = arr[i].

Return

Return max.

📜 Pseudocode

Pseudocode
function findMax(arr):   // assume length >= 1
    max ← arr[0]
    for i from 1 to length(arr) - 1:
        if arr[i] > max:
            max ← arr[i]
    return max
1

Find maximum (reference program)

Matches the reference behavior: reusable findMax function with a sample array and single-pass scan.

c
<?php
function findMax(array $arr): int
{
    $maxVal = $arr[0];
    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] > $maxVal) {
            $maxVal = $arr[$i];
        }
    }
    return $maxVal;
}

$array = [14, 7, 25, 31, 10, 42];
$maxValue = findMax($array);

echo "Maximum value in the array: $maxValue\n";
?>

Explanation

Start from the first element, then compare each next value once. This is a true linear scan, so it is simple and efficient for interview use.

2

When every element is negative

The same function still works: the “maximum” is the least negative value (here −1).

c
<?php
function findMax(array $arr): int
{
    $maxVal = $arr[0];
    foreach ($arr as $value) {
        if ($value > $maxVal) {
            $maxVal = $value;
        }
    }
    return $maxVal;
}

$negatives = [-9, -3, -1, -7];
echo "Maximum (least negative): " . findMax($negatives) . "\n";
?>

Notes

Parallel systems. You can split the array and take the max of partial maxima, then combine—useful for very large data in other environments.

Floating-point. Same structure with double; avoid strict equality when comparing floats for “maximum” in numerical code.

❓ FAQ

It picks an initial candidate from the data so every later comparison has something to beat. After one pass, max holds the largest value seen.
This tutorial assumes size >= 1. With zero elements there is no maximum; return null/throw an exception or validate before calling findMax.
Yes. You still initialize max to the first element; comparisons use > so the largest value (closest to positive infinity among entries) wins—even if every entry is negative.
The scan returns one copy of the maximum value; duplicates do not change which number is printed.
Sorting costs more than O(n) for comparison sorts. A linear scan is enough for max alone.
One pass over n elements: O(n) time and O(1) auxiliary space aside from the input array.

🔄 Input / output

Programs embed literals. To read user input in PHP CLI, parse a line with trim(fgets(STDIN)), split numbers, cast to integers, then pass the array to findMax.

Edge cases

Empty

size == 0

No maximum exists; guard before reading arr[0].

One element

size == 1

The loop body never runs; max_val stays correct as that single element.

⏱️ Time and space complexity

ApproachTimeExtra space
Single scanO(n)O(1)

Summary

  • Algorithm: running maximum from left to right.
  • Cost: O(n) time, O(1) extra space.
  • Edge: define behavior when n = 0.
Did you know?

Finding the maximum in an unsorted array needs at least n − 1 comparisons in the worst case (standard adversary argument). A single left-to-right scan achieves O(n) time and O(1) extra space.

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