xSlart01x
xSlart01x

Reputation: 11

PHP - Declaring vars just one time

I'm asking if it is possible to declare a variable in php just one time. I have the following code but i noticed that everytime i insert something into the form the variables are resetted everytime.

<!doctype html>
<html lang = "English">
    <head>
        <meta charset="UTF-8">
        <title>Array Sum</title>
        <?php 
            $x = 0; 
            $nums[5] = [0, 0, 0, 0, 0];
            $sum = 0;
        ?>
    </head>
    <body>
        <form action="" method="post">
                    <p>
                        Number: <input type = "number" name = "number" size = "40"/> <?php echo " (Number: ", $x+1, ")"; ?>
                    </p>
                    <p>
                        <input type = "submit" name = "send" value = "Send"/>
                        <input type = "reset" name = "cancel" value = "Cancel"/>
                    </p>
                </form>
        <?php 

            echo "-------->DEBUG<--------<br>";
            echo "Var X is set: ", (isset($x)) ? "true" : "false", "<br>";
            echo "Var NUMS is seta: ", (isset($nums)) ? "true" : "false", "<br>";
            echo "Var SUM is set: ", (isset($sum)) ? "true" : "false", "<br>";
            echo "----->END DEBUG<-----<br>";

            if ($x < 5) {
                if (isset($_POST["number"])) {
                        $nums[$x] = $_POST["number"];
                        $x +=1;
                }
            }

            if ($x == 5) {
                for ($index = 0; $index<count($nums); $index++)
                    $sum += $nums[$index];

                echo "<center><b>The sum of the array is : $sum </b></center>";
            }
        ?>
    </body>
</html>

Best regards, Slart.

Upvotes: 0

Views: 55

Answers (1)

yeahgd
yeahgd

Reputation: 58

If you don't specify condition, each time the page is reloaded it will execute all the code. So your $sum will be at zero.

I think you can hold this problem with a session variable like that :

 session_start();

 if (!isset($_SESSION['sum'])) { // It will declare the session's variable "sum" 
     $_SESSION['sum'] = 0;
 }
 else {
     $_SESSION['sum'] += $nums[$index]
 }

I don't really know if it can resolve your problem but it can maybe helps you to find a solution.

Upvotes: 1

Related Questions