Question

PHP – How do I write a code that produces a table of a party cost based on 7 values?

So for example, if min is and max is 60 and cost1 is 5, cost2 is 10, cost3 is 15, cost4 is 20 and cost5 is 25

Was it helpful?

Solution

This should be a good start.

//the (int) changes the input to an integer, which will help prevent code injection.
//$_GET takes variables from the URL string, like http://google.com?min=30&max=60
//$_POST takes variables from a form on the page that then gets submitted <input type="text" name="min" value="30" />
$min = (int) $_GET['min'];
$max = (int) $_GET['max'];

$costs = array(
  '5',
  '10',
  '15',
  '20',
  '25',
);

echo '<table>';

for($i = $min; $i <= $max; $i++)
{
    //if the number is divisible by 5, show it in the table
    if($i % 5 === 0)
    {
        echo '<tr>';
        echo '<td>' . $i . '</td>';

        foreach($costs as $cost)
        {
            echo '<td>' . $cost . '<br>' . $cost * $i . '</td>';
        }

        echo '</tr>';
    }
 }

echo '</table>';

The resulting table will be:

30 150 300 450 600 750

35 175 350 525 700 875

etc... up to and including 60.

OTHER TIPS

Just updated the code above to make sure the min & max values are defined :

<?php
//Added an other line to check if min & max values are defined
//the (int) changes the input to an integer, which will help prevent code injection.
//$_GET takes variables from the URL string, like http://localhost/test.php?min=30&max=60
//$_POST takes variables from a form on the page that then gets submitted <input type="text" name="min" value="30" />
if(isset($_GET['max']) && isset($_GET['min'])){
$min = (int) $_GET['min'];
$max = (int) $_GET['max'];

$costs = array(
  '5',
  '10',
  '15',
  '20',
  '25',
);

echo '<table>';

for($i = $min; $i <= $max; $i++)
{
    //if the number is divisible by 5, show it in the table
    if($i % 5 === 0)
    {
        echo '<tr>';
        echo '<td>' . $i . '</td>';

        foreach($costs as $cost)
        {
            echo '<td>' . $cost * $i . '</td>';
        }

        echo '</tr>';
    }
 }

echo '</table>';
}else echo "Please define the min & max values";
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top