Find Maximum Value (PHP)
Write a PHP function that finds the maximum value in a given array of integers. You cannot use the built-in
max()
function — implement the logic manually with a loop.
Initialize a variable with the first element, then iterate through the rest of the array. If a larger value is found, update the maximum. Return the maximum value. For an empty array, return null or handle accordingly.
This problem demonstrates basic array iteration in PHP using
foreach
or a
for
loop with
count()
. Edge cases include a single element, negative numbers, and equal values.
The maximum value problem demonstrates array iteration in PHP. The
count()
function gets the array length, and a
for
loop iterates through elements. Manual max tracking avoids using the built-in
max()
function.
The manual maximum value problem teaches array traversal in PHP. Using
count()
to get the array length and a
for
loop to iterate demonstrates basic PHP array operations. The null return for empty arrays uses PHP's nullable return type. The algorithm handles negative numbers, duplicates, and single-element arrays correctly.
Example Input & Output
Empty array returns null.
Single element.
Max is -1.
All equal.
Max is 9.
Algorithm Flow

Solution Approach
Handle the empty array case first: use count($nums) to check if the array has no elements, and return null if it does. This prevents undefined index access when trying to read $nums[0].
Initialize the maximum variable with the first element $nums[0]. Then loop through the remaining elements starting at index 1 up to count($nums) - 1. At each iteration, compare the current element with the stored maximum. If the current element is larger, update the maximum.
This manual approach avoids using PHP's built-in max() function and teaches fundamental array traversal. A foreach loop could also be used, but the for loop with count() gives explicit control over indices and is useful when the index position matters.
Edge cases include a single-element array (the loop doesn't execute, the first element is returned), all equal values (the maximum is that value), and negative numbers (the algorithm correctly finds the largest, e.g., -1 is larger than -5). The null return for empty arrays is a PHP convention for "no result".
The time complexity is O(n) with a single pass through the array. The space complexity is O(1) using only one extra integer variable.
Best Answers
<?php
function findMax($nums) {
if (count($nums) === 0) return null;
$max = $nums[0];
for ($i = 1; $i < count($nums); $i++) {
if ($nums[$i] > $max) $max = $nums[$i];
}
return $max;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
