8

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.

Adrian Wiik
  • 469
  • 1
  • 5
  • 16
Daniel Kilburn
  • 167
  • 1
  • 4
  • 13
  • 3
    This is normally faster in SQL. You might wanna look into firing off queries to count – Sammaye Sep 21 '12 at 11:27
  • 1
    can you post your code where you struggling – Surace Sep 21 '12 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 – Daniel Kilburn Sep 21 '12 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 – Baba Sep 21 '12 at 11:30
  • i meant i've not started writing the bit to count it – Daniel Kilburn Sep 21 '12 at 11:31
  • mate first step is to try and if you struggle then google then if you can't find the solution then ask question where you struggling. – Surace Sep 21 '12 at 11:31
  • @DanielKilburn: The short answer: `SELECT some, fields FROM DB.tbl WHERE certain = condition` and `$resultArray = $stmt->fetchAll(PDO::FETCH_ASSOC); echo count($resultArray);` – Elias Van Ootegem Sep 21 '12 at 11:33
  • You could improve your code using only one start- and one end-phptag for each div. It helps to get through the code more easily. – svennergr Sep 21 '12 at 11:44

2 Answers2

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.

Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • 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 Feb 10 '13 at 17:08
  • 1
    @mir You're able to add "use" to get variables from the outside scope. – Berry Langerak Feb 11 '13 at 08:58
  • Downvoted for not being an answer to the original question which was: * how to count array elements that satisfy a condition – Szczepan Hołyszewski Apr 20 '17 at 16:38
  • 1
    @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? – Berry Langerak May 23 '17 at 06:16
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.

svennergr
  • 800
  • 1
  • 8
  • 26