Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count the column of array

In this array output, how can I count the type column? Or better, how can I exclude the addition_data when counting it? Answer should be 3 since there are only 3 type column

Array (
    [124] => 
        Array (
            [type] => 0
            [value] => 4 Pack
            [label] => 4 Pack
            )
    [125] => 
        Array (
            [type] => 0
            [value] => 6 Pack
            [label] => 6 Pack
        )
    [126] => 
        Array (
            [type] => 0
            [value] => 12 Pack
            [label] => 12 Pack
        )
    [additional_data] => {"swatch_input_type":"text","update_product_preview_image":"1","use_product_image_for_swatch":0} )

Tried
count(array_column($swatchLists, 'type'));

But it’s outputting 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way would be to filter out the items with array_filter:

$input = [
  124               => [ 'type' => 0, 'value' => '4 Pack', 'label' => '4 Pack' ],
  125               => [ 'type' => 0, 'value' => '6 Pack', 'label' => '6 Pack' ],
  126               => [ 'type' => 0, 'value' => '12 Pack', 'label' => '12 Pack' ],
  'additional_data' => '{"swatch_input_type":"text","update_product_preview_image":"1","use_product_image_for_swatch":0}'
];

$items = array_filter(
  $input,
  fn($value, $key) => is_int($key) && array_key_exists('type', $value),
  ARRAY_FILTER_USE_BOTH
);

echo count($items);   // Output: 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading