Check if array contains value greater than a number in PHP

This tutorial will discuss about unique ways to check if array contains value greater than a number in php.

Table Of Contents

Method 1: Using array_filter() function

Suppose we have an array of numbers and we want to find if any value in this array is greater than a given number or not. For this, we can use array_filter() function.

The array_filter() function accepts an array and a callback function as arguments. It then applies the callback function on all the elements of the array and returns in new array containing only those elements for which the callback function return true.

So, to find values in an array which are greater than a given number, we can pass the array and the callback function to the array_filter() function. This callback function will accept a value as an argument and returns true if the value is greater then the given number.

So in this case, the array_filter() function will return array containing values more than the given number. Then we can check if this array is empty or not. If it is not empty, then it means that it contains a value greater than the given number.

Let’s see the complete example,

<?php
$number = 15;
$arr = array(12, 14, 6, 18, 10, 8, 9);

// Filler values from for which callback function returns true
$newArr = array_filter(
                    $arr,
                    function($value) use ($number) {
                        return $value > $number;});

if (!empty($newArr)) {
    echo "Yes, the array contains a value greater than the given number";
} else {
    echo "No, the array does not contains a value greater than the given number";
}
?>

Output

Yes, the array contains a value greater than the given number

Method 2: Using foreach()

We can iterate our all the elements of array using foreach(), and during iteration, for each value we can check if it is greater than the given number or not. As soon as we find a value bigger than the provided number, we can mark the result as true and break the loop.

So, in the end of the loop we can check if our result value is true. If yes, then it means that the array contains a value greater than the given number.

Let’s see the complete example,

<?php
$number = 15;
$arr = array(12, 14, 6, 18, 10, 8, 9);

$result = false;
foreach ($arr as $value) {
    if ($value > $number) {
        $result = true;
        break;
    }
}

if ($result) {
    echo "Yes, the array contains a value greater than the given number";
} else {
    echo "No, the array does not contains a value greater than the given number";
}
?>

Output

Yes, the array contains a value greater than the given number

Summary

We learned about two ways to check if an array contains a value greater than the given number in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top