Jump to content

Which is best?


Lineman

Recommended Posts

Ok, here's a real n00b question for you all. I hope you don't mind!

 

Have been practicing with variables and have come across two different ways to call them.  For instance, if i was to create a variable called numbers and the give it a value of.....736 for example,  see the code below:

 

<?php

$numbers = 736;
print ($numbers);
print "<br><br>";
print "$numbers";

?>

 

The two different methods above of calling the variable would both output: 736 but which is considered the best method? Thanks!

Link to comment
Share on other sites

The parenthesis are usually used for multiple things like math equations

 

print (5+6)*2; // output = 22

 

So you can use them or not use them depending on your preference, but if you are only outputting one thing them the less typing you have to to the better. :)

 

also variables don't have to be in quotes

 

print $numbers;

 

Ray

Link to comment
Share on other sites

When echo'ing/print'ing variable you do not need to use quotes or parentheses. Either of the following is fine:

<?php

echo $var; // no need to use quotes when echo'ing a variable on its own

echo "<b>$var</b>"; // variables are parsed in strings which start with double quotes.

echo '<b>'. $var . '</b>'; // variables are not parsed in strings which start with single quotes. Instead you can use concatenation.

?>

 

NOTE: echo and print are the same. print was derived from Perl

Link to comment
Share on other sites

To elaborate on wildteen there is a difference between using single quotes and double quotes. Single quotes treat everything inside exactly as they are. So

 

$name = "Ray";
echo 'My name is $name';  // will output My name is $name
echo "My name is $name";  // will output My name is Ray

 

Also double quotes allows you to use brackets for array pieces and special codes like a line break so your source code is not all on the same line

 

$r['name'] = "Ray";
echo "My name is {$r['name']}<br>\n";
echo "Hello $name";

 

when you view your source code now it will look like

 

My name is Ray<br>
Hello Ray

 

instead of

My Name is Ray<br>Hello Ray

Link to comment
Share on other sites

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.