'PHP - How to toggle a change on click of submit button?

Any ideas why the code below does not give current value of statement after submit button is pressed?

php:

if(isset($_POST["switch"])) {
    if($nm === "off"){
        $nm = "on";
    }
    else{
        $nm = "off";
    }
}

html:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="submit" value="[ -= toggle =- ] <?php echo $nm;?>" id="tt" name="switch">
</form>


Solution 1:[1]

The issue is here:

    $nm = "off";
if(isset($_POST["switch"])) {
    if($nm == "off"){
        $nm = "on";
    }
    if($nm == "on"){
        $nm = "off";
    }
}

remove all that, and change it to:

$nm = isset($_POST["switch"]) ? "on" : "off";

Because you are simply checking what $nm is set to currently, and you set it to "off" in the beginning, it will always be OFF in your secondary if statement...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Green Black