Dev.Wol Dev.Wol - 23 days ago 6
PHP Question

Count number of values in an array where not 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.

Answer

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