Ignatius Samuel Megis
Ignatius Samuel Megis

Reputation: 185

Create array with for and sum total

I stuck here

i wanna sum total from checked checkbox value, and i use array

$check=$_POST[check];
$hit=count($check);
for($h=0;$h<=$hit-1;$h++) {
echo $check[$h];
//output without array : 1,2,3
//i wanna create array ex : $array = array('1', '2', '3');
//and sum total with echo array_sum($array);
//and total is 6
}

how to generate or create array from my loop ?

Upvotes: 0

Views: 54

Answers (2)

Mark Miller
Mark Miller

Reputation: 7447

You say you want to create an array like $array = array('1', '2', '3');, but according to your code you already have that array, ie $check == array('1', '2', '3'); I'm not too clear on what your question is, but assuming that

$check is equal to $_POST[check] is equal to array('1', '2', '3');

then here is no need for count() or loops or creating another array. You just need one line:

$sum = array_sum($check); // 6

See demo

Upvotes: 3

Rakesh kumar
Rakesh kumar

Reputation: 135

You can get the sum like this -

$sum = '';
for($h=0;$h<$hit;$h++) {
    $sum += $check[$h];
}
echo $sum;

Upvotes: 0

Related Questions