0

I think I'm close with my code but I am trying to get the count() from the array provided... total users and OS

        $users = array();
        if ($results = $dbh->runQuery($sql)) {

foreach ($results as $key=>$row){
        $users[$row['user_id']][] = array('user_id'=>$row['user_id'],
        'email' => $row['email'],
        'last_login' => $row['last_login'],
        'fname' => $row['fname'],
        'lname' => $row['lname'], 
        'role_id' => $row['role_id'],
        'role_name' => $row['role_name'],
        'os_d_token' => $row['os'],
        'roid_d_token' => $row['roid'],
        'p_name' => $row['p_name']);
            }
        }

Get total count of users

    $user_cnt = count($row['user_id']);

Get total count of users with OS

    $total_os = '';
    if($row['os'] != null || '-1') {

        $total_os = count($row['os']);

    }
6
  • 1
    why not just count the $results array? Commented Oct 8, 2018 at 16:09
  • 1
    $row['os'] is not an array.. maybe use a COUNT in the SQL query? Commented Oct 8, 2018 at 16:09
  • 1
    or use a incrementing counter Commented Oct 8, 2018 at 16:09
  • 1
    If you are making unique user entries with $users[$row['user_id']][]... then you may be wanting count($users) to find the end result of unique users? Commented Oct 8, 2018 at 16:10
  • 1
    @acctman after you are done with the foreach, you can do that, and it should give you the count of users by unique user_id (as you have it). However getting count of unique OS would require a bit more like MattS's answer. Commented Oct 8, 2018 at 16:47

1 Answer 1

2

count does not retain a counter for you. It immediately returns the number of items in an array. Since you're already looping, set counter variables:

$total = 0;
$total_os = 0;
foreach ($results as $key=>$row) {
    $total++;
    if ($row['os'] != null || $row['os'] != '-1') {
        $total_os++;
    }
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would add the $total++; code within the current foreach statement that I have running correct?

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.