Jump to content

[SOLVED] including variables in an echo statement


dbx

Recommended Posts

Since I started coding in PHP I have been including variables in echo statements like this:

 

echo "My name is ".$name." and I am 5 years old";

 

I've just realised that I can simply type:

 

echo "My name is $name and I am 5 years old";

 

Can anyone tell me why I would have been doing it the first way? Is it the proper way to do it? From a previous version? Did I just pick the wrong tutorial to read? =(

 

Thanks

Can anyone tell me why I would have been doing it the first way?
Because you like to type the extra characters and you like to solve syntax errors that are easier to make using that syntax.

 

The second method is simpler and results in fewer typo's that produce syntax errors. However, sometimes php needs help in figuring out where variables start and stop using the second method and you will need to surround them with {}. You need to do this with array variables and with single variables that have characters following them that are valid for a variable name but are not part of that actual variable name.

using the {} tell php that there going to be a start and stop of a varable,

so in essance it good code pratace to use {} when echo varable statements........

<?php

$mes="hi there im redarrow";

echo "what your name $mess"; // this tell php echo a varable regardless if it there or not.......

echo "<br>";

echo "what your name {$mess}"; //  {} this tell php there a start and stop statement within a varable.....

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.