Search code examples
phpvariablesechoserversuperglobals

Why differences in output using SUPERGLOBAL in PHP?


I am getting error by running following code:

<?php
    //superglobal.php

    foreach($_SERVER as $var=>$value)
    {
        echo $var=>$value.'<br />';     //this will result in to following error: 
                                                    //Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ';' in 
                                                    //C:\xampp\htdocs\w_j_gilmore\CH_03_PHP_BASICS\superglobal.php on line 6
    }
?>

And following code runs successfully

<?php
    //superglobal.php

    foreach($_SERVER as $var=>$value)
    {
        echo "$var=>$value<br />";  
    }
?>

Printing in single quotation and double quotation is difference. WHY?


Solution

  • The difference between the 2 is that in the first you are trying to use the => operator (which is not valid in that place, so will result in a syntax error), while in the second you print a string which happens to have the characters = and > in it.

    The second effectively could be rewritten as:

    <?php
        //superglobal.php
    
        foreach($_SERVER as $var=>$value)
        {
            echo $var . "=>" . $value . "<br />";  
        }
    ?>
    

    If you are just trying to output $_SERVER for debug reasons, I suggest using var_dump or print_r

    var_dump($_SERVER);