Monday, August 16, 2010

Echo with variables in PHP

Standard PHP allows you to embed variables like $myvar right into the echo. But when you have array variables like $_SERVER['PHP_AUTH_USER'], you will have error "Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in ...".

Actually there is a very simple way to embed such a variable. What you need to do is to simply enclose the variable within the echo with curley braces like example below.

echo "This is the Auth user {$_SERVER['PHP_AUTH_USER']} that was logged in";

compare with the string concate format (dot format) below

echo "This is the Auth user ". $_SERVER['PHP_AUTH_USER'] . " that was logged in";

Neat? It save the trouble from the dot format especially if you have a lot of these variables in the line.

Now if you really have a lot variable in multiple lines to echo, you can use the following instead.

echo <<<>

This is the Auth user {$_SERVER['PHP_AUTH_USER']} that was logged in

MYCODE

Notice that there is absolutely no quotation marks any where.

Beware that white spaces is not removed if you use this method.

No comments:

Post a Comment