This is an PHP array:
array
'ItemId' =>
array
0 => string '32' (length=2)
1 => string '33' (length=2)
2 => string '35' (length=2)
'ItemQty' =>
array
0 => string '2' (length=1)
1 => string '1' (length=1)
2 => string '1' (length=1)
What I like to achieve is to count the numbers in the strings in ItemQty
So here the outcome would be 4.
I tried to use a foreach loop but the outcome is always 3 not 4 (logical I think, but cant solve it)
The array above is a small version of a var_dump of POST values. Its for form validation.
$count_total = 0;
foreach ($jcart->get_contents() as $item) {
++$count_total;
}
What is also seems to make complicated is that $jcart->get_contents() is not just an normal array. At least I don't now how to apply it to the solutions beneath.
var_dump($jcart); gives an object in which the total is already stored as well
private 'itemCount' => int 4
Use array_sum()
.
$sum = array_sum($arr['ItemQty']);
This will do it:
$sum = 0;
foreach ($array['ItemQty'] as $val) {
$sum += $val;
}
If you simply want to sum the numbers you can utilise array_sum()
, if it's a single dimensional array. Or, alternatively, you can use a foreach
loop and iterate through it whilst adding to a sum
var, like so:
$sum = 0;
foreach($item in $items) {
$sum += $item;
}
Since your question can also mean count all values in an array. You can use PHP's count()
function to count the total values in an array.
How about something like:
echo array_sum(array_map('intval', $data['ItemQty']))
This will call intval()
for each item in the $data['ItemQty']
array and then call array_sum
to give you the sum of the result.