Jump to content

Sum of the value getting from array in foreach


Sanjib Sinha

Recommended Posts

I want to get sum of the cost of products that one selects through check box. I would like to know whether it is possible to get or not?

Here is the part of the codes.  In index page I have a form that has checkbox of multidimensional array like this:

# <input type=”checkbox” name=”book[0][0]” value=”1″> Old Man and the Sea
# <br>
# <input type=”checkbox” name=”book[0][1]” value=”1″> Gitanjali
# <br>
# <input type=”checkbox” name=”book[0][2]” value=”1″> Forever Yours
# <br>
# <input type=”checkbox” name=”book[0][3]” value=”1″> The Alchemist
# <br>
# </p>

 

Next in ProductClass.php I have a method like GetBooks(), here is the code:

# //getting products individually
# public function GetBooks($book){
# $this->_product = $book;
# if (is_array($_POST) && count($_POST)>1 && is_array($_POST['book'])){
# $message = ”;
#
# foreach ($_POST['book'] as $key_1 => $val_1){
# foreach ($val_1 as $key_2 => $val_2){
# $product_array = array (0=>array(“Old Man and the Sea”, “Gitanjali”, “Forever Yours”,”The Alchemist”));
# $product_name = $product_array[$key_1][$key_2];
# $product_cost = array (0=>array(12.00,09.87,11.50,23.00));
# $cost = $product_cost[$key_1][$key_2];
# $message .= “</p>\n<p>The cost of $product_name is $cost”;
# }
# echo $message. ‘<hr>’;
# }
# }
# else {
# echo “You did not pick up any Book!”;
# }
# }

 

Next in action1,php the form processed and I get the name of the books and their costs. The code is :

if (isset ($_POST['submit'])){

if ($_POST['prod'] != “”){

$product = $_POST['prod'];

$prod = new ProductClass();

echo ‘You chose for ‘ . $prod->GetProduct($product);

}

else {

echo ‘You did not choose anything from textbox!<br>’;

}
}

 

The code works fine. I get the books that I selected through checkbox and I get their prices also. I want to get their sums. Is it possible? Any idea?

I thought, if I would clarify a little bit, it will be much easier to understand. Suppose I select two checkboxes, two name of books with their respective prices will appear.

Now I want to get the sum of the prices of that two books as well.

Since it has come out from an array as an integer in a foreach loop, I can not use array_sum() or something like that.

you have the same value="1" in all of them... you could use that field for the price:

<input type=”checkbox” name=”book[0][0]” value=”5.00″> Book1
<br>
<input type=”checkbox” name=”book[0][1]” value=”7.00″> Book2

 

and then use something like:

 

$sum = 0;
foreach($_POST['book'] as $price){
   $sum += $price[$i];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.