Finding the Biggest Number in an Array of Objects in PHP

If you have an array of objects, such as products, you might want to find the biggest (or, conversly, smallest) number for some reason; you may want to show the biggest price so you can output “Prices Up To: £x” (or “Prices From: £x” with the smallest number). There are a couple of ways to do this.

Approach 1: Iterating Through the Array

This is the obvious way to go before putting too much thought into it; iterate through the array in a loop and keep track of the biggest number seen so far, like this:

$biggest_number = 0;
foreach($products as $product){
  if($product->price > $biggest_number){
    $biggest_number = $product->price;
  }
}
echo "The biggest number is: $biggest_number";

In this example, we use a foreach loop to iterate through the array and compare each number to the biggest number seen so far. This approach has a time complexity of O(n log n), where n is the size of the array.

Approach 2: Using max() and array_column()

A better way is to combine max() and array_column() functions to extract the maximum value. Here’s how:

$biggest_number = max(array_column($products, "price"));
echo "The biggest number is: $biggest_number";

Here we use the array_column() function to extract the price column from an array of objects and then use the max() function on the new array. If you want to find the smallest number, simply replace max() with min().

This approach has a time complexity of O(n), where n is the size of the array. This makes it the most efficient of the two approaches, especially for large arrays.


We'd love to hear from you!

If you think Bronco has the skills to take your business forward then what are you waiting for?

Get in Touch Today!

Discussion

Add a Comment

Get in touch