Member Avatar for LastMitch

Hi

I am trying to understand how to write a If and Else statement correctly regarding sale tax or tax exemptions on certain items for example fruits.

For example:

Here is a demo check out:

  • QTY--items - Price - Total
  • 6 apple - $0.89 (each) = $5.34
  • 6 orange - $0.89 (each) = $5.34
  • 6 Kiki - $0.89 (each) = $5.34
  • 8 tomato - $0.89 (each) = $7.12
  • 6 banana - $0.89 (each) = $5.34
  • 8 onion - $0.89 (each) = $7.12
  • 6 lettuces - $0.89 (each) = $5.34
    Overall Total : $40.94

Here is a sale tax I wrote for CT which is 8.75%

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}

How do I write if the fruits(items) cost over $30 there no exemption but if the fruits(items) cost less than $30 is exemption.

The sale tax for the item that is less than $30 is 4.5%.

Back to the code that I wrote above now I add the following line:

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}
else if ($totalCost > 0 && $totalCost <= 50){$taxx = round($totalCost * .00475,2);}

Here is the question about how to exempted foods.

I take away tomatos, onions and lettuces because their not fruits.

But the apples, oranges, kiki and bananas are fruits.

The total cost for the fruits that I mention above is $21.36.

It's less than $30 so it's exempted and the sale tax is 4.5%

How do I separate the fruits and vegatables above the demo check out?

How do I add or write the code again? Here is it again

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}
else if ($totalCost > 0 && $totalCost <= 50){$taxx = round($totalCost * .00475,2);}

Do I have to do an 'array' or establish a 'var function' in order to separate the fruits and vegetable? Do I need to create a item# to separate the fruits and vegetable? I really do appreciate if someone explained to me how write this correctly? `

Recommended Answers

All 115 Replies

Member Avatar for diafol

tomatoes are fruits :)

Member Avatar for LastMitch

Are they? I didn't know

You can use AND statements in your if statement to sort out what yo

If I'm understanding correctly, it should be fairly simple:

if ($totalfruit > 30){
    $totalcost = round($totalfruit * .08875,2) + $totalother;
    }

else{
    $totalcost = $totalfruit + $totalother;
    }

Yes, tomato is a fruit. Included in dicotyledon fruit group along with apples, plums, pears, oranges and few others.

Member Avatar for diafol

Here's a sample. It's rough and ready, but just an idea:

<?php
function listItems($input){
    //CONFIG ARRAY
    $foods = array(
        "fruit" =>  array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
        "vegetable"=>   array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
    );

    //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
        $key = $item[0];
        $qty = $item[1];
        if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
            $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
            $unit = $foods[$type]['items'][$key];
            $cost = number_format($qty * $unit,2);
            $output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
            $running[$type] += $cost;
        }
    }
    //DO TOTALS FOR OUTPUT
    //1) Tax
    if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
        $fruit_tax_label =  $foods['fruit']['tax_ex_rate'] . "%";
    }else{
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
        $fruit_tax_label =  $foods['fruit']['tax_rate'] . "%";
    }
    if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
        $vegetable_tax_label =  $foods['vegetable']['tax_ex_rate'] . "%";
    }else{
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
        $vegetable_tax_label =  $foods['vegetable']['tax_rate'] . "%";
    }
    $total_tax = $tax['fruit'] + $tax['vegetable'];

    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];

    //3) Bill Total
    $total_bill = $total_sales + $total_tax;

    //BUILD TOTAL HTML
    $total = 
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";

    return "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
}


$input = array(array("tomatoes",6),array("lettuces",6),array("onions",7),array("bananas",30));



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>
<style>
td.right{
    text-align:right;   
}

</style>
</head>

<body>

<?php
echo listItems($input);
?>
</body>
</html>
commented: Thanks for the idea! +0
Member Avatar for LastMitch

Hi elbeato, Thanks for the reply it sounds right

Member Avatar for LastMitch

Hi Ardav,

You're right 'Tomato' is a fruit but for this example I used it as a vegetable. Wow, you'll like Houdini! I have to really take a look at what you wrote. I'm a bit surprise that you can write a script that quickly based on fruits & vegatables. The only way for me to learn a php language is to study how, like you and other members at dani web explained things. Thanks, I appreacite that you took your time to write something like that. I'll get back to you Ardav in a couple of days.

Member Avatar for LastMitch

Hi Ardav,

I realize that you estabish an array and created 2 other array within an array.

function listItems($input){
"fruit" => array("items"=>array(
'apples'=>0.89,
'bananas'=>0.89,
'kiwis'=>0.89,
'oranges'=>0.89),
"tax_ex_limit"=> 30, 
"tax_ex_rate"=>4.5, 
"tax_rate"=>8.75),

"vegetable"=> array("items"=>array(
'tomatoes'=>0.89,
'lettuces'=>0.89,
'onions'=>0.89),
"tax_ex_limit"=> false, 
"tax_ex_rate"=>0, 
"tax_rate"=>8.75)

If someone was to buy a fruit and add to the cart and checkout. Does that fruit array will automatically know that it will be on the list? Ok let me rephrase what I meant. I mean I have to create an array of items and put the price with it then when someone checkout the item, it will know that it's a fruit and if it's less than $30 then it's exempted?

For the "if & else" for the taxes, I didn't know that I can estsblish that in the fruit array with the tax_ex_limit

Hey Ardav, if you have time, when you do have time to reply back can you let me know that I'm getting close to understand what you wrote

What do you mean rough and ready? You mean the script is writing very efficient?

How is that checkout data stored? Sorry in advance if code tags don't work

Here is a demo check out:

QTY--items - Price - Total
6 apple - $0.89 (each) = $5.34
6 orange - $0.89 (each) = $5.34
6 Kiki - $0.89 (each) = $5.34
8 tomato - $0.89 (each) = $7.12
6 banana - $0.89 (each) = $5.34
8 onion - $0.89 (each) = $7.12
6 lettuces - $0.89 (each) = $5.34
Overall Total : $40.94

What Ardav has written has done alot of the groundwork for you, you just need to copy the function as is then change the input array to the actual data from your checkout:

$input = array(array("tomatoes",6),array("lettuces",6),array("onions",7),array("bananas",30));

to match your example:

$input = array(array("apples",6),array("oranges",6),array("Kiwis",6),array("tomatoes",8),array("bananas",6),array("onions",8),array("lettuces",6));

Then you print out the table of data by calling the function and passing the $input data to it

echo listItems($input);

On your original question you would write this if

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}
else if ($totalCost > 0 &amp;&amp; $totalCost &lt;= 50){$taxx = round($totalCost * .00475,2);}

would be written like this:

<?php 
if($sstat == "CT"){
    if($totalCost >= 30){
        $taxx = round($totalCost * .08875,2);
    }elseif($totalCost > 0){
        $taxx = round($totalCost * .00475,2);
    }else{
        //bad value
    }   
}else{
    //$sstat != "CT"
}
?>

From what you are saying though, the items need to be added up into their different tax categories first as a subtotal, then the correct tax needs to be applied to them separately then add up the totals for the correct total amount, what ardav has written will do that for you - it just needs to be rewritten into the function so it can return the subtotals and total cost as a variable you can use.

quick example would be to replace this line:

return "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";

with:

$returndata = array();
$returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
$returndata['totaltax'] = $total_tax;
$returndata['totalsales'] = $total_sales;
$returndata['totalbill'] = $total_bill;
return $returndata;

Now your function will return an array of data so this part needs changing:

echo listItems($input);

it will look like this:

$basketdata = listItems($input);
//echo $basketdata['totaltax'];//print out total tax
//echo $basketdata['totalsales'];//print out total sales
//echo $basketdata['totalbill'];//print out the total cost including tax
//echo $basketdata['html'];//print out the html table that is written in the function
commented: Very Detailed Explanation on how the array runs +2

All together you'll have this:

<?php
function listItems($input){
    //CONFIG ARRAY
    $foods = array(
        "fruit" =>  array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
        "vegetable"=>   array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
    );
    //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
        $key = $item[0];
        $qty = $item[1];
        if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
            $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
            $unit = $foods[$type]['items'][$key];
            $cost = number_format($qty * $unit,2);
            $output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
            $running[$type] += $cost;
        }
    }
    //DO TOTALS FOR OUTPUT
    //1) Tax
    if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
        $fruit_tax_label =  $foods['fruit']['tax_ex_rate'] . "%";
    }else{
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
        $fruit_tax_label =  $foods['fruit']['tax_rate'] . "%";
    }
    if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
        $vegetable_tax_label =  $foods['vegetable']['tax_ex_rate'] . "%";
    }else{
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
        $vegetable_tax_label =  $foods['vegetable']['tax_rate'] . "%";
    }
    $total_tax = $tax['fruit'] + $tax['vegetable'];
    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];
    //3) Bill Total
    $total_bill = $total_sales + $total_tax;
    //BUILD TOTAL HTML
    $total = 
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";
    $returndata = array();
    $returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
    $returndata['totaltax'] = $total_tax;
    $returndata['totalsales'] = $total_sales;
    $returndata['totalbill'] = $total_bill;
    return $returndata;
}

//your checkout items need to go in here into $input
$input = array(array("apples",6),array("oranges",6),array("Kiwis",6),array("tomatoes",8),array("bananas",6),array("onions",8),array("lettuces",6));
//$input = array(array("tomatoes",6),array("lettuces",6),array("onions",7),array("bananas",30));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>
<style>
td.right{
    text-align:right;   
}
</style>
</head>
<body>
<?php
$basketdata = listItems($input);

echo "Subtotal: {$basketdata['totalsales']}<br/>\r\n";//print out total sales
echo "Added Tax: {$basketdata['totaltax']}<br/>\r\n";//print out total tax
echo "Total: {$basketdata['totalbill']}<br/><br/>\r\n";//print out the total cost including tax
echo $basketdata['html'];//print out the html table that is written in the function
?>
</body>
</html>
Member Avatar for LastMitch

Hi Biiim,

Thanks for the reply! I appreciate you taking your time to explain and going over what "ardav" wrote and I will get back to you in a couple days.
Thanks man!

Member Avatar for LastMitch

Hi Biiim,

I'm still working on the code but if I need more explaination I will post it here and thanks again for replying!

Member Avatar for LastMitch

Hi Biiim,

I have a couple of questions

1) function listItems($input)

  • Do I have to replace '$input' to another term in order for the script to work properly?

I think you mention checkout data stored. My $input is actually a $sku to identify the item.

2) Ok, for example:

if the fruits(items) cost less $30 there is an exemption but if the fruits(items) cost more than $30 is no exemption.

if($sstat == "CT"){
if($totalCost <= 30){
$taxx = round($totalCost * .0,2);
}elseif($totalCost > 30){
$taxx = round($totalCost * .08875,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}

Is that right?

3) I like the way you separate the

$tax ['fruit']
$tax ['vegetable']

I think I have a minor issue with the tax. How do I replace the $taxx to $total_taxx. I can't seem to connect the array to the $taxx. So it's still charging taxes for fruits(items) cost less $30 * .08875 not exempted

$total_sales = $running['vegetable'] + $running['fruit'];

The array you wrote above I try to change it to mines but it won't work.

Instead this is the one I have on my script. This is the line I wrote:

$totalCost += ($row["qty"] * $row["price"]);

I appreciate your insight again!

Member Avatar for LastMitch

Hi Biiim,

I forgot to mention this if

$input = array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89)

is it the same as what you wrote:

$input = array(array("apples",6),array("oranges",6),array("Kiwis",6),array("bananas",6),);

meaning that I have to write array("apples",6) in front of the item for the array to work properly?

1) function listItems($input)

no the variable name $input can stay the same - or it can be different. it just needs to be the array of your basket items

2) Ok, for example:

The tax is auto worked out via the function now, the parts that work it out are here:

$foods = array(
       "fruit" =>  array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
       "vegetable"=>   array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
     );

tax_ex_limit is the value it can go up to to fit into the exempt tax rate on the other it is false meaning there isnt one.
Defined just after at 4.5% the full tax rate defined at 8.75%

 if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
    $fruit_tax_label =  $foods['fruit']['tax_ex_rate'] . "%";
 }else{
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
    $fruit_tax_label =  $foods['fruit']['tax_rate'] . "%";
 }

 if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
     $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
     $vegetable_tax_label =  $foods['vegetable']['tax_ex_rate'] . "%";
 }else{
     $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
     $vegetable_tax_label =  $foods['vegetable']['tax_rate'] . "%";
 }

That treats vegetables and fruit separately and if the fruit is over the exempt rate it will charge the full rate.

if you want to see the tax rate charged you could update the bottom part here:

$returndata = array();
$returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
$returndata['totaltax'] = $total_tax;
$returndata['totalsales'] = $total_sales;
$returndata['totalbill'] = $total_bill;
return $returndata;

to this:

$returndata = array();
$returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
$returndata['veg_tax_label'] = $vegetable_tax_label;
$returndata['fruit_tax_label'] = $fruit_tax_label;
$returndata['totaltax'] = $total_tax;
$returndata['totalsales'] = $total_sales;
$returndata['totalbill'] = $total_bill;
return $returndata;

The outside of the function you access them with $basketdata['fruit_tax_label'] or $basketdata['veg_tax_label']

Hi Biiim,

I forgot to mention this if

$input = array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89)

is it the same as what you wrote:

$input = array(array("apples",6),array("oranges",6),array("Kiwis",6),array("bananas",6),);

meaning that I have to write array("apples",6) in front of the item for the array to work properly?

Yes they are different.

$testarray = array("apples",6);
foreach($testarray as $key=>$value){
    echo "{$key} => {$value}<br/>\r\n";
}

This creates an array with 2 values, a string "apples" and an integar 6. the string is given an index or "Key" of 0 and the intergar has a key of 1

$testarray2 = array("apples"=>6);
foreach($testarray2 as $key=>$value){
    echo "{$key} => {$value}<br/>\r\n";
}

This creates an array with 1 value, the intergar 6. It's given a key of "apples"

The function ardav wrote needs the 2 values with the default index's of 0 and 1 to work properly

commented: I appreciated your explanation! +0
Member Avatar for LastMitch

Hi Biiim,

I appreciated that you reply again. I few more questions:

This array has the the item and price

$input = array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89)

This array means that the item is "apples" and the integer is '6' meaning 6 apples?

$input = array(array("apples",6),array("oranges",6),array("Kiwis",6),array("bananas",6),);

For the array to work the ('apples'=>0.89) and ("apples",6) has to match in order to work. It also means that if I have alot items I have to enter the
the same way like this ('apples'=>0.89) for all of the items. For the ("apples",6) I also have to enter the same amount. For example: I enter 100 items like this way ('apples'=>0.89) and to match it I also have to enter 100 items like this way("apples",6)

Is this like a filter array but a difficult one?

For the taxes

<?php
if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}
?>

Once I established the taxes above. The $food and $vegetable below has to be the same as the taxes above?

$foods = array(
"fruit" => array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
"vegetable"=> array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
);

I also have a question regarding about the total cost or total sales:

This is the part of the script that is from the example above calculate the '$total_tax' and '$total_sales'

$total_tax = $tax['fruit'] + $tax['vegetable'];
$total_sales = $running['vegetable'] + $running['fruit'];

This part is the script I have on my script that calculate the '$totalCost' ('$total_tax' and '$total_sales')

$ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;
<?php echo number_format($totalCost + $ship + $taxx, 2, ".", ","); ?>

How do I merge or change a few words from '$total_tax' and '$total_sales' to the '$totalCost' on my script in order for the calculate the $taxes (meaning separate $fruit and $vegetable taxes) and also calculate the '$ordertotal' (sub-total) in order to work correctly?

I appreciate your insight again! I will test out the formula that you mention above and figure out how to match the modify the scripts. It's pretty difficult! I never thought certain php formula sound and look so simple from a pdf file but in the real world it's so much different.

Member Avatar for LastMitch

Hi Biiim,

You mention that:

The tax is auto worked out via the function now, the parts that work it out are here:

$foods = array(
"fruit" => array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
"vegetable"=> array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
);

So I don't really need this anymore:

<?php
if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}
?>

I'm a bit confused. I'm still configuring the taxes.

$foods = array(
"fruit" => array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
"vegetable"=> array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)
);

This array is a list of all the items available to purchase in your shopping cart, hopefully you dont have more than fruit & vegetables or it will get more complex. To be most efficient the array should be created from a database, so you dont have to update the array at all it just changes as products are added, removed and edited on the site. It should also probably use a product id as well rather than a name, but the name for now is good at understanding it easier. Using arrays like this is just a way to get the thing working before linking it into a database of the products. Heres a quick example

$Q = "SELECT product_id,product_cat,product_name,product_price FROM `products`";
$R = mysql_query($Q);
$foods = array();
while($prod = mysql_fetch_assoc($R)){
    $foods[$prod['product_cat']]['items'] = array($prod['product_id'],$prod['product_price']);  
}

//this data should come from a category table
$foods['vegetable']['tax_ex_limit'] = false;
$foods['fruit']['tax_ex_limit'] = 30;
$foods['vegetable']['tax_ex_rate'] = 0;
$foods['fruit']['tax_ex_rate'] = 4.5;
$foods['vegetable']['tax_rate'] = 8.75;
$foods['fruit']['tax_rate'] = 8.75;
var_dump($foods);

Then when adding things to the shopping cart, add them into an array using the product_id and the quantity wanted ie. instead of array("apples",6); it would become array(1,6); assuming apples have an id of 1 - this is if it is easy to change the shopping cart - stick to using the name as the unique key of the products table if it isn't easy to change.

$ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;
<?php echo number_format($totalCost + $ship + $taxx, 2, ".", ","); ?>

just change that to:

$ordertotal = $basketdata['totalbill'] + $_SESSION["ship"] + $express + $gift;
<?php echo number_format($totalCost + $ship + $taxx, 2, ".", ","); ?>

totalbill includes the tax

$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);

are them taxes correct? the first one is 8.875% tax and the second is 0.475% tax, Ardav put in 8.75% tax and 4.5% tax - i assumed he knew about the tax over there.

the function basically adds up all the fruit and veg separately, then if the fruit is over $30 will add the increased tax onto the fruit. billtotal will show the correct taxed value whichever case. Try running some test baskets and work out the cost yourself and check the script returns the same value

commented: Thanks for the example +0
Member Avatar for LastMitch

Hi Biiim,

I appreciate that you're taking your time to explained this to me, yes the 'array' was a bit too much for me to handled. The category table that you wrote I got a image of how the tax exemption works. I can tell you, your example was much easier to understand than 'Ardav'.
I haven't complie script yet to see overall what I did yet. So far the results been frustrating all I been doing is trying to figure out what 'Ardav' wrote and I really want to "Thank you" for taking your time to explained his work. I think you knew 'Ardav' example was too hard for me to understand! I'll get back to you once I follow your direction and used 'product_id' instead of fruits & vegetable. I appreciate your insight again!

Member Avatar for diafol

Thrice thou hast taken my name in vain. With great vengeance shall thou be smote. :)

commented: Enjoy the Holy Tomato of Antioch! +2
Member Avatar for LastMitch

"And the Daniweb spake, saying, "First shalt thou take out the Holy Pin. Then, shalt thou count to three. No more. No less. Three shalt be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, nor either count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then, lobbest thou thy Holy Tomato of Antioch towards thy foe, who, being naughty in My sight, shall snuff it." =)

So that's how you get Ardav back from a holiday.

Member Avatar for LastMitch

Hi Biiim,

If you like I send you a freight of 'Holy Tomato of Antioch' over in UK! Maybe can you lob to Ardav.
I'm still working on the tax exemption I'll actually still following the instructions that you wrote and if I have any questions I post here. Thanks again!

Member Avatar for LastMitch

Hi Biiim,

I think I realized that I didn't mention in more detail about the taxes.

For example:

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}

My Total Cost is written like this:

$totalCost += ($row["qty"] * $row["price"]);

When you written the example a couple weeks back I realized now that the 'Total Cost' * tax rate.

This tax rate is just for 1 crown colony (US state = CT) = (sstat == "CT")

The issue I been having is that $totalCost * tax rate then I realize that I just want the 'fruit' & 'vegatable' get tax then * 'Total Cost'

Meaning if the fruit is less than 30 than the tax is at .00475 if it's more the tax rate .08875. For the vegatable it's at .08875.

I think I just need instead of the $totalCost * tax rate I need how to write the what you wrote:

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}

instead of the total cost it's the fruit taxes * round($totalCost)

Which is fruit is less than 30 than the tax is at .00475 if it's more the tax rate .08875.

Then for the vegatable it's just .08875.

You're right about it might get complicate if I do have more than 1 category. I also have Exotic Fruits and Organic.

That's why I just used fruits & vegetables.

I try input this:

//this data should come

from a category table
$foods['vegetable']['tax_ex_limit'] = false;
$foods['fruit']['tax_ex_limit'] = 30;
$foods['vegetable']['tax_ex_rate'] = 0;
$foods['fruit']['tax_ex_rate'] = 4.5;
$foods['vegetable']['tax_rate'] = 8.75;
$foods['fruit']['tax_rate'] = 8.75;
var_dump($foods)

I used array from 'Ardav' like you explained to me to do.

"fruit" => array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
"vegetable"=> array("items"=>array('tomatoes'=>0.89,'lettuces'=>0.89,'onions'=>0.89),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75)

Then it dump a list of foods out.

It works! It show the lists of fruits & vegetables which was kinda neat

I can't figure out how to write the fruit is less than 30 than the tax is at .00475 if it's more the tax rate .08875. For the vegatable it's at .0887

I appreciate your insight again!

getting there!

The ingenious function Ardav wrote actually already handles that

"fruit" => array("items"=>array('apples'=>0.89,'bananas'=>0.89,'kiwis'=>0.89,'oranges'=>0.89),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),

You see the settings towards the end of the array

"tax_ex_limit" is the point where full tax kicks in this is set to $30
"tax_ex_rate" is the tax to be applied if it stays below this limit
"tax_rate" is the full tax rate when it goes over the $30 limit

Can you post a full copy of the page so we can see what you've got all together now? leave any passwords or ip addresses out of it for security

It's a little hard to advise without seeing what you've currently got

commented: Rep from me for all the hard work and patience +14
commented: Biim been doing alot of explanation +0
Member Avatar for diafol

The ingenious function Ardav wrote actually already handles that

:) Very kind!

@Biiim
I'm loathe to make a comment on this thread as you've been extremely patient and helpful - so will let you get on with it. I just hope that you get a shedload of rep points. All power to you!

@LastMitch

Your mother was a hamster and your father smelled of elderberries

One of my fave films of all time too :)

Just to point out - I'm sorry that you found the original code so complicated. I included everything as arrays as I thought that would help 'compartmentalize' data, so that you wouldn't have tens and tens of stray variables all over the place. As we are using procedural code, there is no 'object' so data can get spread over a range of variables quite easily and if you don't take care with naming conventions, it could all end in tears! An OOP approach to this would be ideal, but as you're starting out, perhaps sticking to 'simple' procedural code would be best.

commented: Ardav, I never knew you like elderberries +0
Member Avatar for LastMitch

Hi Biiim,

Here is the script that I been configuring:

<?php
session_start();
header("Cache-control: private");
require_once ('include/init.php');

if (isset($_POST['ins'])) {
if (!isset($_POST['promo'])) {$promo="no";} else {$promo="yes";}

$sstat = $_POST["stat"];

$sql="INSERT INTO cust(fname, lname, email, addr, city, stat, zip, promo, phone, dt, country) VALUES (".
  "'".mysql_real_escape_string(trim($_POST["fname"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["lname"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["email"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["addr"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["city"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["stat"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["zip"]))."', ".
  "'".$promo."', ".
  "'".mysql_real_escape_string(trim($_POST["phone"]))."',NOW(),'".trim(mysql_real_escape_string($_POST["country"]))."') ";

$rs= mysql_query($sql);

$uid = mysql_insert_id();
$_SESSION['uid'] = $uid;

$country = trim($_POST["country"]);
$_SESSION['country'] = trim($_POST["country"]);

if (mysql_affected_rows()<0){
    print "<B>Fatal ERROR: Could not add customer.</B>";
    exit();
}};
        if (isset($_POST['place'])) {   

           $sql="SELECT * from cust where id = ".mysql_real_escape_string($_SESSION['uid']);
           $rs= mysql_query($sql) ;
           echo mysql_error();
           $row=mysql_fetch_array($rs);
           $eemail = $row["email"];
           $country = $row["country"];

          if ($_POST["express"] == "15"){$express = 15; $expyes = "yes";}else{$express = 0; $expyes = "no";}
          if ($_POST["gift_wrap"] == "5"){$gift_wrap = 5; $giftyes = "yes";}else{$gift_wrap = 0; $giftyes = "no";}

          $ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;

          $_SESSION["mthis"] ="" ;
          $_SESSION["mthis"] .=$row["fname"]." ".$row["lname"]."\n" ;
          $_SESSION["mthis"] .=$row["addr"]."\n".$row["city"].", ".$row["stat"].", ".$row["zip"].", "."\n" ;
          $_SESSION["mthis"] .=$row["country"]."\n".$row["email"]."\n".$row["phone"]."\n"."\n"."Order info:"."\n" ;

          $sql="INSERT INTO orders(cust_id, cart_total, taxx, shipping, express, gift_wrap, s_first, s_last, s_addr, s_city, s_stat, s_zip, s_email, s_country, dt, s_phone) VALUES (".
          "'".mysql_real_escape_string($row["id"])."', ".
          "'".mysql_real_escape_string($ordertotal)."', ".
          "'".mysql_real_escape_string($_SESSION["taxx"])."', ".
          "'".mysql_real_escape_string($_SESSION["ship"])."', ".
          "'".mysql_real_escape_string($expyes)."', ".
          "'".mysql_real_escape_string($giftyes)."', ".
          "'".mysql_real_escape_string($row["fname"])."', ".
          "'".mysql_real_escape_string($row["lname"])."', ".
          "'".mysql_real_escape_string($row["addr"])."', ".
          "'".mysql_real_escape_string($row["city"])."', ".
          "'".mysql_real_escape_string($row["stat"])."', ".
          "'".mysql_real_escape_string($row["zip"])."', ".
          "'".mysql_real_escape_string($row["email"])."', ".
          "'".mysql_real_escape_string($row["country"])."',NOW(),'".mysql_real_escape_string($row["phone"])."') ";

$rs= mysql_query($sql,$o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

          $oid = mysql_insert_id();

          $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");

            if (mysql_num_rows($result)==0){
            echo mysql_num_rows($result);}
            while($row = mysql_fetch_array($result)){

             $_SESSION["mthis"] .=$row["itemName"]."\n" ;
             $_SESSION["mthis"] .="itemNumber: ".$row["itemNumber"]."\n" ;
             $_SESSION["mthis"] .="Qty: ".$row["qty"]."\n" ;    
             $_SESSION["mthis"] .="gift_wrap: ".ucwords($row["gift_wrap"])."\n" ;
             $_SESSION["mthis"] .="Unit Price: ".$row["price"]."\n"."\n" ;  

             $sql="INSERT INTO order_details(o_id, prod_id, name, itemNumber, qty, gift_wrap, unitprice, total) VALUES (".
              "'".mysql_real_escape_string($oid)."', ".
              "'".mysql_real_escape_string($row["itemId"])."', ".
              "'".mysql_real_escape_string($row["itemName"])."', ".
              "'".mysql_real_escape_string($row["itemNumber"])."', ".
              "'".mysql_real_escape_string($row["qty"])."', ".
              "'".mysql_real_escape_string($row["gift_wrap"])."', ".
              "'".mysql_real_escape_string($row["price"])."', ".
              "'".mysql_real_escape_string($row["price"]*$row["qty"])."') ";      
$rs= mysql_query($sql, $o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
            }

            $_SESSION["mthis"] .="Shipping = $ ".$_SESSION["ship"]."\n" ;
            $_SESSION["mthis"] .="Express Shippig = $ ".$expyes."\n" ;
            $_SESSION["mthis"] .="gift_wrap = $ ".$giftyes."\n" ;
            if ($taxx != ""){$_SESSION["mthis"] .="Tax = $ ".$taxx."\n" ;}  
            $_SESSION["mthis"] .="Total = $ ".$ordertotal."\n" ;    
            $_SESSION["mthis"] .="........................................"; 
                }
        ?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <style type="text/css"> 
         <!--
        .style1 {font-family: "Times New Roman", Times, serif; font-size: 12px;color: #333333;}
        .style5 {color: #FFFFFF}
        .style8 {font-size: 10px}
         --> 
         </style>
        <script language="javascript">
        function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + '$' + num + '.' + cents);
        }

        function calcFees(chk,cost){if (chk.checked == 1){
            document.getElementById("stotal").innerHTML = formatCurrency(cost + 15);} else{
            document.getElementById("stotal").innerHTML = formatCurrency(cost);}}
        function calcFees1(chk,cost){if (chk.checked == 1){
            document.getElementById("stotal").innerHTML = formatCurrency(cost + 5);} else{ 
            document.getElementById("stotal").innerHTML = formatCurrency(cost);}}
        </script>
</head>
    <body>
                              <? include("header.php");?>
<table width="800" height="298" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#FFFFFF">
  <tr>
    <td height="298" align="center" valign="top"><p><a href="index_09.html"></a></p>
        <table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
          <tr>
            <td width="200" height="25" align="center"><h3 align="center" class="style17">CHECKOUT </h3>
                <p align="center" class="style1">Please verify the info <strong></strong> belo<span class="style42">w</span>: <br>
                    <br>
              </p></td>
          </tr>
        </table>
      <div align="center">
          <form action="checkout2.php?" method="post">
<?php
    function GetCartId(){
        // This function will generate an encrypted string and
        // will set it as a cookie using set_cookie. This will
        // also be used as the cookieId field in the cart table
        if(isset($_COOKIE["cartId"])){
            return $_COOKIE["cartId"];}
        else{
            // There is no cookie set. We will set the cookie
            // and return the value of the users session ID
            session_start();
            setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
            return session_id();}}

    $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");
 ?>
            <table width="78%" border="0" align="center" cellpadding="3" cellspacing="0" bgcolor="#CCCCCC">
              <tr>
                <td width="15%" height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">ITEM NUMBER</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">ITEM</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">QTY</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">SUBTOTAL</span></td>
              </tr>
              <? 
if (mysql_num_rows($result)==0){
echo mysql_num_rows($result);
    }
$_SESSION["mthis"] ="";
while($row = mysql_fetch_array($result)){
// Increment the total cost of all items
$foods = array();
$totalCost += ($row["qty"] * $row["price"]);
$ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;

if($sstat == "CT"){$taxx = round($ordertotal * .08875,2);}

    function listItems($input){
    //CONFIG ARRAY
    $foods = array(
    "fruit"=> array("items"=>array(
    //Fruit--------------------
    //Apple----------
    //Cortland
    'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
    //Ginger Gold 
    'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75, 
    //Idared
    'A-I01'=>35, 'A-I02'=>50, 'A-I03'=>75, 
    //McIntosh
    'A-M01'=>35, 'A-M02'=>50, 'A-M03'=>75, 
    //Grapefruit
    'G-001'=>35, 'G-002'=>50, 'G-003'=>75,
    //Lemon
    'L-001'=>35, 'L-002'=>50, 'L-003'=>75,
    //Orange
    'O-001'=>35, 'O-002'=>50, 'O-003'=>75,  
    //Pears 
    'P-001'=>35, 'P-002'=>50, 'P-003'=>75, 
    //Tangerine
    'T-001'=>35, 'T-002'=>50, 'T-003'=>75,   
    //Asian Pears 
    'P-A01'=>55, 'P-A02'=>105, 'P-A03'=>165, 
    //Guava
    'G-V01'=>55, 'G-V02'=>105, 'G-V03'=>165,  
    //Kiwi
    'K-001'=>55, 'K-002'=>105, 'K-003'=>165,  
    //Mango
    'M-001'=>55, 'M-002'=>105, 'M-003'=>165,  
    //Papaya
    'P-P01'=>55, 'P-P02'=>105, 'P-P03'=>165, 
    //Pomegranate
    'P-001'=>55, 'P-002'=>105, 'P-003'=>165,   
    //Star fruit
    'S-001'=>55, 'S-002'=>105, 'S-003'=>165,    
    //Cantaloupe
    'C-001'=>55, 'C-002'=>95, 'C-003'=>120, 
    //Honey Dew
    'H-001'=>55, 'H-002'=>95, 'H-003'=>120, 
    //Watermelon
    'W-001'=>55, 'W-002'=>95, 'W-003'=>120, 
    //Banana
    'B-001'=>35, 'B-002'=>50, 'B-003'=>75, 
    //Lychee
    'L-Y01'=>55, 'L-Y02'=>105, 'L-Y03'=>165,
    //Cranberry 
    'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
    //Raspberry
    'R-B01'=>20, 'R-B02'=>30, 'R-B03'=>50, 
    //Cherry ---------
    //Black 
    'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
    //Chelan
    'C-C01'=>20, 'C-C02'=>30, 'C-C03'=>50, 
    //Sweet Cherry
    'C-S01'=>20, 'C-S02'=>30, 'C-S03'=>50, 
    //Grapes----------
    //Purple
    'G-P01'=>20, 'G-P02'=>30, 'G-P03'=>50, 
    //Red
    'G-R01'=>20, 'G-R02'=>30, 'G-R03'=>50, 
    //White
    'G-W01'=>20, 'G-W02'=>30, 'G-W03'=>50, 
    )),

    "vegetable"=> array("items"=>array(
    //Vegetable--------------------
    //Asparagus
    'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80, 
    //Broccoli
    'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80, 
    //Carrots
    'C-A01'=>35, 'C-C02'=>55, 'C-C03'=>80, 
    //Celery
    'C-E01'=>35, 'C-E02'=>55, 'C-E03'=>80, 
    //Cucumber
    'C-U01'=>35, 'C-U02'=>55, 'C-U03'=>80,  
    //Eggplant
    'E-P01'=>35, 'E-P02'=>55, 'E-P03'=>80, 
    //Garlic
    'G-L01'=>35, 'G-L02'=>55, 'G-L03'=>80, 
    //Ginger
    'G-G01'=>35, 'G-G02'=>55, 'G-G03'=>80, 
    //Green Bean
    'G-B01'=>35, 'G-B02'=>55, 'G-B03'=>80, 
    //Iceberg Lettuce 
    'I-L01'=>35, 'I-L02'=>55, 'I-L03'=>80, 
    //Lettuce 
    'L-T01'=>35, 'L-T02'=>55, 'L-T03'=>80, 
    //Tomoto
    'T-O01'=>35, 'T-O02'=>55, 'T-O03'=>80, 
    //Potato
    'P-O01'=>35, 'P-O02'=>55, 'P-O03'=>80, 
    //Onion
    'O-N01'=>35, 'O-N02'=>55, 'O-N03'=>80, 
    //Snow pea 
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
    //Soybean 
    'S-B01'=>35, 'S-B02'=>55, 'S-B03'=>80,  
    //Spinach
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
    //Squash
    'S-Q01'=>35, 'S-Q02'=>55, 'S-Q03'=>80, 
    //Sweet Corn
    'S-C01'=>35, 'S-C02'=>55, 'S-C03'=>80,   
    //Sweet Potato
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80,    
    //Chinese Long Beans
    'CH-LB01'=>45, 'CH-LB02'=>90, 'CH-LB03'=>175, 
    //Chinese Kai-lan
    'CH-KL01'=>45, 'CH-KL02'=>90, 'CH-KL03'=>175, 
    //Chinese Pak choy
    'CH-PC01'=>45, 'CH-PC02'=>90, 'CH-PC03'=>175, 
    //Chinese Taro
    'CH-TA01'=>45, 'CH-TA02'=>90, 'CH-TA03'=>175, 
    //Chinese Water Chestnut
    'CH-WC01'=>45, 'CH-WC02'=>90, 'CH-WC03'=>175, 
    //Chinese Winter melon
    'CH-WM01'=>45, 'CH-WM02'=>90, 'CH-WM03'=>175, 
    )) );
     //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
    $key = $item[0];
    $qty = $item[1];
    if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
    $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
    $unit = $foods[$type]['items'][$key];
    $cost = number_format($qty * $unit,2);
    $output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
    $running[$type] += $cost;
    }}
    //DO TOTALS FOR OUTPUT
    //1) Tax
    if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
    $fruit_tax_label = $foods['fruit']['tax_ex_rate'] . "%";
    }else{
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
    $fruit_tax_label = $foods['fruit']['tax_rate'] . "%";
    }
    if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
    $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
    $vegetable_tax_label = $foods['vegetable']['tax_ex_rate'] . "%";
    }else{
    $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
    $vegetable_tax_label = $foods['vegetable']['tax_rate'] . "%";
    }
    $total_tax = $tax['fruit'] + $tax['vegetable'];
    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];
    //3) Bill Total
    $total_bill = $total_sales + $total_tax;
    //BUILD TOTAL HTML
    $total =
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";
    $returndata = array();
    $returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
    $returndata['veg_tax_label'] = $vegetable_tax_label;
    $returndata['fruit_tax_label'] = $fruit_tax_label;
    $returndata['totaltax'] = $total_tax;
    $returndata['totalsales'] = $total_sales;
    $returndata['totalbill'] = $total_bill;
    return $returndata;
    }
    //your checkout items need to go in here into $input
    $input = array(
    //Apple----------
    //Cortland = 36 per box / 72 per box / 84 per box 
    array('A-C01',1),array('A-C02',1),array('A-C03',1),
    //Ginger Gold = 36 per box / 72 per box / 84 per box 
    array('A-G01',1),array('A-G02',1),array('A-G03',1),
    //Idared = 36 per box / 72 per box / 84 per box 
    array('A-I01',1),array('A-I02',1),array('A-I03',1),
    //McIntosh = 36 per box / 72 per box / 84 per box 
    array('A-M01',1),array('A-M02',1),array('A-M03',1),
    //Grapefruit = 36 per box / 72 per box / 84 per box 
    array('G-001',1),array('G-002',1),array('G-003',1),
    //Lemon = 36 per box / 72 per box / 84 per box 
    array('L-001',1),array('L-002',1),array('L-003',1),
    //Orange = 36 per box / 72 per box / 84 per box  
    array('O-001',1),array('O-002',1),array('O-003',1), 
    //Pears  = 36 per box / 72 per box / 84 per box 
    array('P-001',1),array('P-002',1),array('P-003',1), 
    //Tangerine = 36 per box / 72 per box / 84 per box 
    array('T-001',1),array('T-002',1),array('T-003',1),  
    //Asian Pears = 24 per box / 48 per box / 60 per box 
    array('P-A01',1),array('P-A02',1),array('P-A03',1), 
    //Guava = 24 per box / 48 per box / 60 per box  
    array('G-V01',1),array('G-V02',1),array('G-V03',1),  
    //Kiwi = 24 per box / 48 per box / 60 per box  
    array('K-001',1),array('K-002',1),array('K-003',1), 
    //Mango = 24 per box / 48 per box / 60 per box 
    array('M-001',1),array('M-002',1),array('M-003',1),  
    //Papaya = 24 per box / 48 per box / 60 per box 
    array('P-P01',1),array('P-P02',1),array('P-P03',1), 
    //Pomegranate = 24 per box / 48 per box / 60 per box 
    array('P-001',1),array('P-002',1),array('P-003',1),   
    //Star fruit = 24 per box / 48 per box / 60 per box 
    array('S-001',1),array('S-002',1),array('S-003',1),    
    //Cantaloupe = 10 per box / 20 per box / 30 per box 
    array('C-001',1),array('C-002',1),array('C-003',1),
    //Honey Dew = 10 per box / 20 per box / 30 per box 
    array('H-001',1),array('H-002',1),array('H-003',1),
    //Watermelon = 10 per box / 20 per box / 30 per box 
    array('W-001',1),array('W-002',1),array('W-003',1),
    //Banana = 24 per box / 48 per box / 60 per box 
    array('B-001',1),array('B-002',1),array('B-003',1),
    //Lychee = 24 per box / 48 per box / 60 per box 
    array('L-Y01',1),array('L-Y02',1),array('L-Y03',1),
    //Cranberry = 24 per box / 48 per box / 60 per box 
    array('C-B01',1),array('C-B02',1),array('C-B03',1),
    //Raspberry = 24 per box / 48 per box / 60 per box 
    array('R-B01',1),array('R-B02',1),array('R-B03',1),
    //Cherry ---------
    //Black = 24 per box / 48 per box / 60 per box 
    array('C-B01',1),array('C-B02',1),array('C-B03',1), 
    //Chelan = 24 per box / 48 per box / 60 per box 
    array('C-C01',1),array('C-C02',1),array('C-C03',1), 
    //Sweet Cherry = 24 per box / 48 per box / 60 per box 
    array('C-S01',1),array('C-S02',1),array('C-S03',1), 
    //Grapes----------
    //Purple = 24 per box / 48 per box / 60 per box 
    array('G-P01',1),array('G-P02',1),array('G-P03',1), 
    //Red = 24 per box / 48 per box / 60 per box 
    array('G-R01',1),array('G-R02',1),array('G-R03',1), 
    //White = 24 per box / 48 per box / 60 per box 
    array('G-W01',1),array('G-W02',1),array('G-W03',1), 
    //Vegetable--------------------
    //Asparagus = 24 per box / 48 per box / 60 per box 
    array('A-A01',1),array('A-A02',1),array('A-A03',1), 
    //Broccoli = 24 per box / 48 per box / 60 per box 
    array('B-B01',1),array('B-B02',1),array('B-B03',1), 
    //Carrots = 24 per box / 48 per box / 60 per box 
    array('C-A01',1),array('C-C02',1),array('C-C03',1), 
    //Celery = 24 per box / 48 per box / 60 per box 
    array('C-E01',1),array('C-E02',1),array('C-E03',1), 
    //Cucumber = 24 per box / 48 per box / 60 per box 
    array('C-U01',1),array('C-U02',1),array('C-U03',1), 
    //Eggplant = 24 per box / 48 per box / 60 per box  
    array('E-P01',1),array('E-P02',1),array('E-P03',1), 
    //Garlic = 24 per box / 48 per box / 60 per box 
    array('G-L01',1),array('G-L02',1),array('G-L03',1), 
    //Ginger = 24 per box / 48 per box / 60 per box 
    array('G-G01',1),array('G-G02',1),array('G-G03',1), 
    //Iceberg Lettuce = 24 per box / 48 per box / 60 per box 
    array('I-L01',1),array('I-L02',1),array('I-L03',1), 
    //Lettuce = 24 per box / 48 per box / 60 per box 
    array('L-T01',1),array('L-T02',1),array('L-T03',1),
    //Tomoto = 24 per box / 48 per box / 60 per box 
    array('T-O01',1),array('T-O02',1),array('T-O03',1), 
    //Green Bean = 2 lb / 4 lb / 8 lb
    array('G-B01',1),array('G-B02',1),array('G-B03',1), 
    //Potato = 2 lb / 4 lb / 8 lb
    array('P-O01',1),array('P-O02',1),array('P-O03',1),
    //Onion = 2 lb / 4 lb / 8 lb
    array('O-N01',1),array('O-N02',1),array('O-N03',1),
    //Squash =  2 lb / 4 lb / 8 lb
    array('S-Q01',1),array('S-Q02',1),array('S-Q03',1), 
    //Snow pea = 4 lb / 7 lb / 10 lb
    array('S-P01',1),array('S-P02',1),array('S-P03',1), 
    //Soybean = 4 lb / 7 lb / 10 lb
    array('S-B01',1),array('S-B02',1),array('S-B03',1),  
    //Spinach =  4 lb / 7 lb / 10 lb
    array('S-P01',1),array('S-P02',1),array('S-P03',1), 
    //Sweet Corn = 4 lb / 7 lb / 8 lb
    array('S-C01',1),array('S-C02',1),array('S-C03',1),  
    //Sweet Potato = 4 lb / 7 lb / 8 lb
    array('S-P01',1),array('S-P02',1),array('S-P03',1),   
    //Chinese Long Beans =  3 lb / 7 lb / 10 lb
    array('CH-LB01',1),array('CH-LB02',1),array('CH-LB03',1),
    //Chinese Kai-lan = 3 lb / 7 lb / 10 lb
    array('CH-KL01',1),array('CH-KL02',1),array('CH-KL03',1), 
    //Chinese Pak choy =  3 lb / 7 lb / 10 lb
    array('CH-PC01',1),array('CH-PC02',1),array('CH-PC03',1),
    //Chinese Taro =  3 lb / 7 lb / 10 lb
    array('CH-TA01',1),array('CH-TA02',1),array('CH-TA03',1),
    //Chinese Water Chestnut =  3 lb / 7 lb / 10 lb
    array('CH-WC01',1),array('CH-WC02',1),array('CH-WC03',1),
    //Chinese Winter melon = 10 per box / 20 per box / 30 per box 
    array('CH-WM01',1),array('CH-WM02',1),array('CH-WM03',1),
    );
    ?>
              <tr>
       <td height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"><?php echo $row["itemNumber"]; ?></font></span></td>
                <td width="57%" height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> <?php echo $row["itemName"]; ?> - <font face="verdana"><?php echo $row["size"]; ?></font></font></span></td>
            <td width="11%" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> <?php echo $row["qty"]; ?> </font></span></td>
                <td width="15%" height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> $<?php echo number_format($row["price"]*$row["qty"], 2, ".", ","); ?></font></span></td>
              </tr>
              <?php
}

$domestic = array('United States');

if(in_array($_POST['country'],$domestic)){
//----------Domestic Shipping--------------//
if ($totalCost > 0 && $totalCost <= 100){$ship = 6.50;}
if ($totalCost > 100 && $totalCost <= 300){$ship = 10.50;}
if ($totalCost > 300 && $totalCost <= 500){$ship = 14.00;}
if ($totalCost > 500 && $totalCost <= 700){$ship = 18.00;}
if ($totalCost > 700 && $totalCost <= 1000){$ship = 20.00;}
if ($totalCost > 1000){$ship = 25.00;}
}else{
//----------International Shipping--------------//
if ($totalCost > 0 && $totalCost <= 100){$ship = 30.00;}
if ($totalCost > 100 && $totalCost <= 300){$ship = 35.00;}
if ($totalCost > 300 && $totalCost <= 500){$ship = 40.00;}
if ($totalCost > 500 && $totalCost <= 700){$ship = 45.00;}
if ($totalCost > 700 && $totalCost <= 1000){$ship = 50.00;}
if ($totalCost > 1000){$ship = 50.00;} 
}
//----------store important values in session--------------//
    $_SESSION['tcost'] = $totalCost;
    $_SESSION['ship']  = $ship;
    $_SESSION['taxx']  = $taxx;
//----------store important values in session--------------//
?>
              <tr>
                <td colspan="4" bgcolor="#FFFFFF" class="style1"><div align="right">______________________</div></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TAX:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($taxx, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">SHIPPING:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($ship, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
         <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">* EXPRESS DELIVERY: </span></div></td>
         <td bgcolor="#FFFFFF" class="style1"><input name="express" type="checkbox" id="express" onClick="calcFees(express,<?=$totalCost + $ship + $taxx;?>);" value="15"/>
                </td>
              </tr>
              <tr>
            <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">GiFT WRAP ($5): </span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><input name="gift_wrap" type="checkbox" id="gift_wrap" onClick="calcFees1(gift_wrap,<?=$totalCost + $ship + $taxx;?>);" value="5"/>
                </td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TOTAL:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"><b>
                  <div id="stotal">$<?php echo number_format($totalCost + $ship + $taxx, 2, ".", ","); ?></div>
                </b></font></span></td>
              </tr>
            </table>
            <p class="navtitlesm"><strong>* Express Delivery</strong><br>
  For an additional $20, Express orders placed by 9 am ET will be delivered in  the contiguous U.S.<br> 
  in 2 business days for most in-stock.&nbsp;</p>
            <p align="center">
              <input name="place" type="hidden" id="place" value="yes" />
              <input name="tcost" type="hidden" id="tcost" value="<? echo $totalCost; ?>" />
              <input name="ship" type="hidden" id="ship" value="<? echo $ship; ?>" />
              <input name="taxx" type="hidden" id="taxx" value="<? echo $taxx; ?>" />
              <input type="submit" name="Submit" value="Place Order" />
            </p>
          </form>
    </div></td>
  </tr>
</table>
                              <? include("footer.php");?>                       
</body>
</html>
Member Avatar for diafol

Omg. Don't you have a db for storing all this data? Maintaining that array looks scary.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.