Page 1 of 1

PHP Minus biggest number first

Posted: Tue Dec 17, 2013 5:42 am
by wooxie
Hello,

I'm trying to make the biggest numnber in a sum that will be placed at the front of the sum when you make a random sum like this:

if ($1 < $2)
{
$change = $2;
$2 = $ 1;
$1 = $change;
}

In this code:

Code: Select all

<?php
session_start();
if (!isset($_SESSION['questions'])) {
    $_SESSION['questions'] = array(
        'n1' => array(),
        'n2' => array(),
        'ans' => array()
        );
    $_SESSION['count'] = 0;
    
    $numbers = range(1,100);
  
    $arr = array_rand($numbers, 10);
    foreach ($arr as $k) $_SESSION['questions']['n1'][] = $numbers[$k];
    
    $numbers = array_diff($numbers, $_SESSION['questions']['n1']);
    
    $arr = array_rand($numbers, 10);
    foreach ($arr as $k) $_SESSION['questions']['n2'][] = $numbers[$k];
}
if (isset($_POST['ans'])) {
    $_SESSION['questions']['ans'][$_SESSION['count']] = $_POST['ans'];
    ++$_SESSION['count'];
}

?>
<html>
<head>
<title>Math</title>
</head>
<body>

<form method='post' action=''>

<?php
$q = $_SESSION['count']+1;
if ($q < 11) {
    echo <<<EOT
    <h2>+</h2>
    <h5>Question $q</h5>
    {$_SESSION['questions']['n1'][$_SESSION['count']]}
    -
    {$_SESSION['questions']['n2'][$_SESSION['count']]}
    <br><br>
    Your answer: <input type='text' size='3' name='ans'><br>
    <br><br>
    <input name='btnsubmit' type='submit' value='Next'>
    <input name='btnreset' type='reset' value='Delete'>
EOT;
}
else {
    echo "<h5>Results</h5>
        <table border='1' cellpadding='3' style='border-collapse:collapse'>\n
        <tr><td></td><td>Question</td><td>Answer</td><td>Your answer</td><td>Correct</td></tr>\n";
    for ($i=0; $i<10; $i++) {
        $qno = $i+1;
        $qtext = $_SESSION['questions']['n1'][$i] + $_SESSION['questions']['n2'][$i];
        $ans = $_SESSION['questions']['n1'][$i] + $_SESSION['questions']['n2'][$i];
        $yours = $_SESSION['questions']['ans'][$i];
        $chk = $ans==$yours ? '&check;' : '';
        echo "<tr><td>$qno</td><td>$qtext</td><td>$ans</td><td>$yours</td><td>$chk</td></tr>\n";
    }
    echo "</table>\n<br><input name='btnsubmit' type='submit' value='New test'>";
    unset($_SESSION['questions']);
}
?>

</form>
<script type='text/javascript'>
onload = function(){document.forms[0].ans.focus();}
</script>
</body>
</html>

Re: PHP Minus biggest number first

Posted: Tue Dec 17, 2013 1:12 pm
by requinix
You can use min and max like

Code: Select all

$min = min($v1, $v2);
$max = max($v1, $v2);
Then you'd use $min and $max instead of $v1 and $v2.