'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";
}
Solution 1:[1]
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";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pavel |
