Jump to content

[SOLVED] including variables in an echo statement


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.....

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.