Why differences in output using SUPERGLOBAL in PHP?

94 views Asked by At

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?

2

There are 2 answers

0
TiiJ7 On BEST ANSWER

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);
0
Jens W On

You have not quoted the string:

echo $var=>$value.'<br />'; 

quoted would look like this:

echo '$var => $value <br />'; 

if single quoted, variables are not interpreted.