0

I am trying to get a count of active users and unactive users.

First i get all user data: $userData = fetchAllUsers();

Then I write a foreach to get a total of the users who are active and the users who are unactive.

foreach ($userData as $key => $value) {
$active = $value['active'];
if($active == 1){
    $activeUsers = count($active);
    print_r($activeUsers);
} elseif($active == 0) {
    $unactiveUsers =  count($active);
    print_r($unactiveUsers);
}

}

All this prints is 1111111. There are 5 users set to 1 (active) and 2 users set to 0 (unactive) in the database. So I am looking to add these up to be 5 active and 2 unactive.

I have triedcount and array_sum and array_count_values. Nothing seems to be doing what I need. Any help would be appreciate. Can someone guide me in the right direction?

1
  • It seems the data is string, try to force it using (int) $variable Commented Mar 13, 2015 at 19:30

2 Answers 2

5

You're inside a loop, you don't need count. Just increment a counter yourself. And wait until you're done with your loop to spit out the results.

$activeUsers = 0;
$inactiveUsers = 0;

foreach ($userData as $key => $value) {
    $active = $value['active'];
    if($active == 1){
        $activeUsers++;
    } elseif ($active == 0) {
        $inactiveUsers++;
    }
}

var_dump($activeUsers);
var_dump($inactiveUsers);
Sign up to request clarification or add additional context in comments.

3 Comments

Ha you beat me by 18 seconds :-D
@Andy Nice =) And while your code is a bit more terse, I'd argue mine is a tad easier to understand for a beginner.
That worked perfectly! I tried that early today, but the mistake I made was not including this $activeUsers = 0;$inactiveUsers = 0; outside of the foreach.
3

You need to count up a variable, e.g.

$active = 0;
$inactive = 0;

foreach ($userData as $key => $value) {
 switch(true) {
  case $value['active'] == 1: $active++; break;
  default: $inactive++; break;
 }
}

var_dump("Active users" + $active);
var_dump("Inactive users" + $inactive);

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.