×
Create a new article
Write your page title here:
We currently have 3,189 articles on s23. Type your article name above or create one of the articles listed here!



    s23
    3,189Articles
    in:

    PHP/if switch: Difference between revisions

    < PHP
    Content added Content deleted
    imported>mutante
    imported>mutante
    m (adding PHP syntax highlighting)
     
    Line 3: Line 3:
    === if / elseif ===
    === if / elseif ===


    <highlightSyntax>
    <pre>
    if ($fnord == 23) {
    if ($fnord == 23) {
    echo "Found a 23!";
    echo "Found a 23!";
    Line 13: Line 13:
    echo "Nothing special";
    echo "Nothing special";
    }
    }
    </highlightSyntax>
    </pre>


    * http://www.php.net/manual/en/control-structures.elseif.php
    * http://www.php.net/manual/en/control-structures.elseif.php
    Line 21: Line 21:
    === switch / case ===
    === switch / case ===


    <highlightSyntax>
    <pre>
    switch ($fnord) {
    switch ($fnord) {
    case 23:
    case 23:
    Line 35: Line 35:
    echo "Nothing special";
    echo "Nothing special";
    }
    }
    </highlightSyntax>
    </pre>


    * http://www.php.net/switch
    * http://www.php.net/switch

    Latest revision as of 22:10, 22 June 2006

    If you want to compare one variable to multiple values in PHP, you can do so 2 different ways:

    if / elseif[edit]

    <highlightSyntax> if ($fnord == 23) {

      echo "Found a 23!";
    

    } elseif ($fnord == 17) {

      echo "Found a 17!";
    

    } elseif ($fnord == "Foobar") {

      echo "Fnord is a string!";
    

    } else {

      echo "Nothing special";
    

    } </highlightSyntax>

    OR you can do the same like this

    switch / case[edit]

    <highlightSyntax> switch ($fnord) { case 23:

      echo "Found a 23!";
      break;
    

    case 17:

      echo "Found a 17!";
      break;
    

    case "Foobar":

      echo "Fnord is a string!";
      break;
    

    default:

      echo "Nothing special";
    

    } </highlightSyntax>

    read here why you need the "break"


    Which is Faster ?[edit]

    Now, you might wonder, which is "better" to use?


    Look at this Benchmark provided by Shai-Tan comparing them.

    It turns out that the difference is almost not noticable but switch is a tiny bit faster.

    <@Shai-Tan> mutante:  0.00011
    <@Shai-Tan> mutante: a moral victory at best
    < mutante> Shai-Tan: hehe, ok, somehow it also looks better in the source ;)
    <+jome_> Shai-Tan: Hehe, seems your benchmark made it clear that there isn't a difference :>
    

    from #php on EfNet

    Cookies help us deliver our services. By using our services, you agree to our use of cookies.
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.