Page 1 of 1

arraycalculations

Posted: Fri Feb 19, 2010 2:53 pm
by mBull
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


hi

I'm very new to php and I can't get out of this problem.

Code: Select all

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
<body>
<?php
$total = 0;
$order = array( array("cola", 0.85 , 1),
               array("hamburger", 4.95 , 2),
               array("milkshake", 1.95 , 1),
               array("fristi", 1.85, 1)
             );
?>
<table border="1">
  <tr>
    <td><b>Product</b></td>
    <td><b>Amount</b></td>
    <td><b>Price</b></td>
  </tr>
<?php
for ($row = 0; $row < 4; $row++)
{
    echo "<tr>";
    for ($col = 0; $col < 3; $col++)
    {
        echo "<td>".$order[$row][$col]."</td";
    }
    echo "</tr>";
}
 
echo $total;
?>
</table>
</body>
</html>
 
this first part works perfect (it display's an array in a colum)

but I want the folowing to do:
i want that each amout is mulitplied by each price in each row and add to 1 total

i was thinking of something like this, but it wont work:

Code: Select all

 
for ($row=0; $row < 4; $row++)
{
    for ($col = 1; $col < 3; $col++) //because you have to skip the first colom (0) start with 1
    {
        $total += $total + $order[$row] * $order[$col];
    }
}
 
please help me with this one

I'm looking forward to hearing from you guys

thanks

mBull


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: arraycalculations

Posted: Fri Feb 19, 2010 3:06 pm
by pickle
The foreach() construct allows you to loop over arrays without first knowing the size of the array. So, you're close:

Code: Select all

foreach($order as $item)
{
  $total += $item[1] * $item[2];
}

Re: arraycalculations

Posted: Fri Feb 19, 2010 3:20 pm
by mBull
thanks man, it works now

and about the code segment i'll keep in mind next time I post