0

If I have an array such as -

 Products ( 
      'ProductA' (
        'color' => 'red',
        'serial' => '1234a'
      ),

      'ProductB' (
        'color' => 'blue',
        'size' => 'large'
      ),

      'ProductC' (
        'color' => 'green',
        'serial' => '4567b'
      )
    )

is there a way to do something like -

count($products[*]['serial'])

I just need a count of all the products that have the 'serial' index.... using [] and [*] does not work.

4 Answers 4

1
$counter=0;
foreach($products as $product)
{
   if(isset($product["serial"]))
   $counter++;
}
echo $counter;
1

PHP >= 5.5.0 required:

$result = count(array_column($products, 'serial'));
0

You can use array_filter in conjucntion with isset:

$count = count(array_filter($array, function ($v) {
    return isset($v['serial']);
}));
0

Clear solution with array filter

      $products = array(
        'ProductA' => array(
                    'color' => 'red',
                    'serial' => '1234a'
                    ),
        'ProductB' => array(
                    'color' => 'red',
                    'size' => 'large'
                    ),
        'ProductC' => array(
                    'color' => 'red',
                    'serial' => '1234a'
                    ),
            );

    $nr = count(array_filter($products, function($arr) { return !empty($arr['serial']); }));
    echo $filtered;

Hope it helps

1
  • This will not return an accurate count if any 'serial' indices are set to 0 or other "empty-ish" values. Commented Aug 21, 2014 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.