0

I have an array and I'm trying to count the number of objects in the array where the the object key 'Value' is not 0.

array (
  0 => 
  array (
    'name' => 'item[110189]',
    'value' => '0',
    'primary_key' => '110189',
  ),
  1 => 
  array (
    'name' => 'item[110190]',
    'value' => '50',
    'primary_key' => '110190',
  ),
  2 => 
  array (
    'name' => 'item[110191]',
    'value' => '0',
    'primary_key' => '110191',
  ),
  3 => 
  array (
    'name' => 'item[110192]',
    'value' => '0',
    'primary_key' => '110192',
  ),
)

I've tried the following:

$input_items = array_filter($request->items, function($item){

            $count = 0;

            foreach($item as $i){
                if(! $i['value'] == 0){
                    $count = $count + 1;
                }
            }

            return $count;
        }); // it will return an array

        return $input_items;

I get an error saying invalid object 'Value' which to be honest I half expected.

4
  • 1
    Can you update your question with the var_export version of the array? Commented Nov 16, 2016 at 13:44
  • 1
    ! $i['value'] == 0 to $item['value'] != 0 and in the callback $item['value'] no more loop needed, remove the foreach Commented Nov 16, 2016 at 13:45
  • 1
    Thanks @JustOnUnderMillions that seemed to work, I'll save that! Commented Nov 16, 2016 at 13:50
  • @Dev.Wol Check out my answer with the demo. Commented Nov 16, 2016 at 13:53

2 Answers 2

1

Changed it this way:

$input_items = array_filter($arr, function ($item) {
    return ($item['value'] != 0);
});

Full Code

<?php
$arr = array (
  0 => 
  array (
    'name' => 'item[110189]',
    'value' => '0',
    'primary_key' => '110189',
  ),
  1 => 
  array (
    'name' => 'item[110190]',
    'value' => '50',
    'primary_key' => '110190',
  ),
  2 => 
  array (
    'name' => 'item[110191]',
    'value' => '0',
    'primary_key' => '110191',
  ),
  3 => 
  array (
    'name' => 'item[110192]',
    'value' => '0',
    'primary_key' => '110192',
  ),
);
$input_items = array_filter($arr, function ($item) {
    return ($item['value'] != 0);
});

print_r($input_items);

Output has only the non-zero entries:

Array
(
    [1] => Array
        (
            [name] => item[110190]
            [value] => 50
            [primary_key] => 110190
        )

)

Demo: http://ideone.com/LUbMSb

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

Comments

1

You can use array_reduce:

print array_reduce($request->items, function($carry ,$item){
   if($item['value'] != 0){
      $carry++;
   }
   return $carry;
  },0);

Comments

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.