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
https://forums.phpfreaks.com/topic/100174-which-is-best/
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
https://forums.phpfreaks.com/topic/100174-which-is-best/#findComment-512176
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
https://forums.phpfreaks.com/topic/100174-which-is-best/#findComment-512184
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
https://forums.phpfreaks.com/topic/100174-which-is-best/#findComment-512194
Share on other sites

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.