Jump to content

incorrect echo still works


Peter Knight
 Share

Recommended Posts

I noticed an echo statement was coded incorrectly and yet it still worked  :undecided:

Any ideas why the project_managers field outputs properly ...

<?php
  if ($page->projects_managers){
  echo "<strong>Project Managers:</strong> $page->projects_managers </br>";
}
 else{
   echo ""; 
 }
?>

 ...when it should probably be as follows (concatenated)

<?php
  if ($page->projects_managers){
  echo "<strong>Project Managers:</strong>" . $page->projects_managers . "</br>";
}
 else{
   echo ""; 
 }
?>
Link to comment
Share on other sites

A variable in double quotes will get parsed fine. If your first code it was in single quotes you would see $page->projects_managers instead :-). So, the code is not incorrect. I do like to concatenate though for code readability/highlighting..

http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP

Edited by kongondo
  • Like 4
Link to comment
Share on other sites

This is a feature of PHP. String literals with double quotes (") will evaluate the variables within. For clarity, you could also enclose the variable in curly brackets ({}) like so:

echo "You must be the pride of {$subject_hometown}!";

Only if you use single quotes (') the string will be parsed as-is, and you must use concatenation or other string operations to change it. Note that this means that within single quotes, escape sequences will not work either, so you can’t do the following, even though there are no variables in there:

echo '\r';

----

Added by Nico:

More infos: http://stackoverflow.com/questions/10512452/php-using-a-variable-inside-a-double-quotes (and I marked it as solved)

Edited by Nico Knoll
  • Like 5
Link to comment
Share on other sites

You can do this though:

echo '<strong>"Project Managers":</strong>' . my_function($page->projects_managers) . "\r";

In words - you can mix single and double quotes in the same statement. In my theoretical example above I wanted "Project Managers" to be echoed in double quotes, then run a function on $page->project_managers, hence the concatenation, and then use an escaped "\r", which is why I switched from single quotes to double quotes in the same echo statement.

EDIT: Of course you could always use double quotes and escape as needed like below, but I like the above version better:

echo "<strong>\"Project Managers\":</strong>" . my_function($page->projects_managers) . "\r";
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...