8

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.

8
  • 3
    This is normally faster in SQL. You might wanna look into firing off queries to count Commented Sep 21, 2012 at 11:27
  • 1
    can you post your code where you struggling Commented Sep 21, 2012 at 11:27
  • hi guys, i've not actually started writing any code to do this bit i was going to do several queries but thought it would be better do it in php Commented Sep 21, 2012 at 11:29
  • 1
    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 now you are saying ` i've not actually started writing any code` don't know what to believe Commented Sep 21, 2012 at 11:30
  • i meant i've not started writing the bit to count it Commented Sep 21, 2012 at 11:31

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And how do you access an outside variable inside the array_filter subfunction? i.e. instead of using 'X' and 'Y', use a variable I've set outside
@mir You're able to add "use" to get variables from the outside scope.
Downvoted for not being an answer to the original question which was: * how to count array elements that satisfy a condition
@SzczepanHołyszewski I don't really your point, as it did answer the question of the OP. Also, by splitting them up based on condition it's actually pretty simply to count, I guess?
1

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.

1 Comment

That's taken from the manual...come on at least an answer that applies to his scenario...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.