简体   繁体   中英

'if 'condition is true but 'else' is executed

I have an problem with this code :

        <?php $nb = 10; ?>
    <script>
        if(window.innerHeight+1 == screen.height) 
        {
            document.write("<?php $nb = 10; ?>");
            alert("1");
            alert(window.innerHeight +1+ " " +screen.height+ " 1");
        }else{
            document.write("<?php $nb = 8; ?>");
            alert("2");
            alert(window.innerHeight +1+ " " +screen.height + " 2");
        }
   <script>
           <?php

        $blink = "";
        $i = 0;
        for($i=0;$i<$nb;$i++)
        {
            if($_SESSION['Collection'][$i]->getUrgence() == "FORTE")
            {
            $blink = " class=\"Blink\"";
            }
        elseif($_SESSION['Collection'][$i]->getUrgence() == "MOYENNE")
        {
            $blink = "";
        }

        echo '<tr>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getNumDossier().'</td>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getNomTicket().'</td>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getService().'</td>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getImpact().'</td>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getUrgence().'</td>';
        echo    '<td'.$blink.'>'.$_SESSION['Collection'][$i]->getDateOuverture().'</td>';
        echo '</tr>';
        }
    ?>

In fact I want to detect if the browser is in full screen, if it is I put my variable to 10 otherwise I put it to 8. After I use this variable in my php code to display a number of values.

The 'if' is true, alert("1") is been printed but $nb =8, it was really a strange thing no ?

Thank You for reading !

I think you have two competing ideas. As @Titus has stated in his comment all of the PHP code is compiled first. So $nb is first set to 10 and then set to 8.

Once the HTML output is generated $nb is 8 anywhere in the HTML it is used. You need to have an if/else in PHP or use a separate variable.

    <?php $nb = 10; ?>
<script>
    if(window.innerHeight+1 == screen.height) 
    {
        document.write("8");
        alert("1");
        alert(window.innerHeight +1+ " " +screen.height+ " 1");
    }else{
        document.write("8");
        alert("2");
        alert(window.innerHeight +1+ " " +screen.height + " 2");
    }

You should go into your developer tools and inspect the HTML to see what values are generated on the client side. PHP = server side code, JS = client side code (since you aren't using node).

Your intentions for the snippet aren't clear so there isn't a workable example I can give you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM