Home » Php » PHP – Count all elements of an Array that Satisfy a Condition

PHP – Count all elements of an Array that Satisfy a Condition

Posted by: admin July 12, 2020 Leave a comment

Questions:

Possible Duplicate:
Search for PHP array element containing string

I’ve created a mysql query that pulls through several products, all with the following information:

Product ID
Product Name
Product Price
and
Product Category

Further down the page, I’ve looped through these with a foreach and a few ‘ifs’ so it only displays those products where the name contains ‘x’ in one div and displays those products where the name contains ‘y’ in another div.

I’m struggling to count how many products are going to be in each div before I do the loop.

So essentially, what I’m asking is:

How do you count all elements in an array that satisfy a certain condition?

Added Code which shows the loop:

<div id="a">
    <?php
    $i = 1;
    foreach ($products AS $product) {
        if (strpos($product->name,'X') !== false) {
            =$product->name
        }
        $i++;
    } ?>
</div>

<div id="b">
    $i = 1;
    foreach ($products AS $product) {
        if (strpos($product->name,'Y') !== false) {
            =$product->name
        }
        $i++;
    } ?>
</div>

I’d like to know how many of these are going to be in here before I actually do the loop.

How to&Answers:

Well, without seeing the code, so generally speaking, if you’re going to split them anyway, you might as well do that up-front?

<?php
// getting all the results.
$products = $db->query('SELECT name FROM foo')->fetchAll();

$div1 = array_filter($products, function($product) {
    // condition which makes a result belong to div1.
    return substr('X', $product->name) !== false;
});

$div2 = array_filter($products, function($product) {
    // condition which makes a result belong to div2.
    return substr('Y', $product->name) !== false;
});

printf("%d elements in div1", count($div1));
printf("%d elements in div2", count($div2));

// then print the divs. No need for ifs here, because results are already filtered.
echo '<div id="a">' . PHP_EOL;
foreach( $div1 as $product ) {
   echo $product->name;
}
echo '</div>';

echo '<div id="b">' . PHP_EOL;
foreach( $div2 as $product ) {
   echo $product->name;
}
echo '</div>';

That being said: you should take notice of the comment which says “This is normally faster in SQL”, because it is the more sane approach if you want to filter the values.

EDIT: Changed the name of the variables to adapt the variable names in the example code.

Answer:

Use an array-filter: http://www.php.net/manual/en/function.array-filter.php

array array_filter ( array $input [, callable $callback = "" ] )

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

But be aware, this is a loop though, and your the SQL query will be faster.