Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php use switch without break;

Tags:

php

whats wrong with my switch ? Now result:

< more
> less
= equality
!= no't equality 

As it should be:

< more
= equality

<?php
$page = 99;

    switch ($page)
    {
        case $page < 121:
            echo '< more <br/>';
        case $page > 123:
            echo '> less <br/>';
        case $page == 99:
            echo '= equality <br/>';
        case $page != 99:
            echo '!= no\'t equality <br/>';
    }   
    ?>
like image 385
mmarrkota Avatar asked Nov 27 '22 18:11

mmarrkota


1 Answers

In your switch statement you're comparing a number with boolean values.
Let's take the first case $page < 121 is true, so the comparison taking place is 99==true which is true according to http://docs.php.net/language.types.type-juggling (switch performs a loose comparison, not a strict like ===). Thus the first case block is executed.
And since you don't have a break statement it falls through to the next case block and the next and so on...
Meaning: This won't work as intended regardless of whether you use break or not.

like image 158
VolkerK Avatar answered Dec 06 '22 04:12

VolkerK