1

My array is below. What I am trying to do is count the number of nodes in the array have null or 'new' for read_status.

Is there something more sufficient than looping through the array?

Array
(
    [0] => Array
        (
            [id] => 428
            [read_status] => 
        )

    [1] => Array
        (
            [id] => 427
            [read_status] => 
        )
    [2] => Array
        (
            [id] => 441
            [read_status] => new
        )  
    [3] => Array
        (
            [id] => 341
            [read_status] => read
        )  
)

So the count should be 3.

3 Answers 3

2

you could do

$count = count(array_filter($myArray, function($item){
    return $item['read_status'] != 'new';
}));

echo $count;

but I think its more efficient to just loop through it like this:

$count = 0;
foreach($myArray as $item){
    if($item['read_status'] != 'new')$count++;
}

echo $count;
Sign up to request clarification or add additional context in comments.

Comments

1

There is nothing wrong with looping in the array to do this, it might actually be faster than using a generic method to do it for you. It's simply this :

$count = 0;
foreach ($arrays as $entry)
{
    if (!$entry['read_status'] || $entry['read_status'] === "new")
    {
        $count++;
    }
}

echo $count;

7 Comments

Minor improvement: use === instead of ==.
My personal pet peeve of PHP devs is: they're always asking "how do I do X to an array, without looping".
I changed it to ===, might as well.
@TravisO should I not be concerned about looping? I was taught looping was not most efficient. Was I taught wrong? Can you explain why it's your pet peeve?
@DanyCaissy got you. so one way or another, this puppy is looping.
|
0

I actually improved my SQL by removing the null completely -- so now read_status is either read or new.

IF(feed_read.read_status IS NULL,'new','read') AS read_status

From there, I was able to utilize another SO question in order to count the 'new' elements.

$counted = array_count_values(array_map(function($value){return $value['read_status'];}, $result));
echo $counted['new'];

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.