Michael Nkansah
Michael Nkansah

Reputation: 11

how to calculate the total number of values in an array

i have this line of code that is supposed to print out the number of items in an array but rather the result is return only ones of the number. Example of the array contains two values the output will be (11) instead of just (2).

<?php 
if (is_array($responses) && is_countable($responses) && count($responses) > 0) {
    foreach ($responses as $val) {
        if ($val['transaction_status'] == 1) {
            echo count((array)($val['employee_name']));
        }
    }
} else {
    echo "No Active Transactions";
}

Upvotes: 0

Views: 61

Answers (1)

pavel
pavel

Reputation: 27092

You need to make a sum in the loop. Currently you write there 1 in each iteration (it results in 11 instead of 1+1).

$total = 0;
if (is_array($responses) && is_countable($responses) && count($responses) > 0) {
    foreach ($responses as $val) {
        if ($val['transaction_status'] == 1) {
            $total += count((array)($val['employee_name']));
            // Is there really an array and could have more names? 
            // If no, use just $total++ instead.
        }
    }

    echo $total;
} else {
    echo "No Active Transactions";
}

Upvotes: 1

Related Questions