PHP Lesson 04 - setting and printing variables

Started by Parham, August 27, 2003, 08:50:55 PM

Previous topic - Next topic

Parham

I've explained to you what a variable is; now let me show you how to create a variable.  A variable, as stated in the previous lesson, is something which can hold a dynamic value.  A variable is distinguished from other things because it starts with a dollar sign.  For example, "$name" could be a variable which would most likely hold the name of something, someone, or someplace.  Variable declaration requires the use of the "assignment operator" ("=") which will assign a value to our variable.

What you assign to a variable also requires a little thought.  If you're assigning a number to a variable, then quotes are not required.  If you're assigning a string to a variable, then quotes are required.  The two basic types a variable can be are "string" and "number" and PHP understands which one you want with the presence/absence of quotes.


$name = 'Parham'; //this will assign 'Parham' to the variable $name, note the quotes

$number = 12; //this will assign 12 to the variable $number, note the absence of quotes

$othernumber = '12'; //this will assign '12' to the variable $number, not the presence of quotes, the variable is now interpreted as a string, not as a number


If you literally want to use quotes in your strings then they will have to be "escaped" so PHP will not get confused:


$phrase = 'hi my name\'s Parham'; //by placing a \ in front of the single quote, the variable will now be set properly and you will not receive errors


Here is how PHP will read the above, step by step:
-Interpret right side of assignment operator first
-see a single quote, recognize this as a string, continue until you find another quote
-found a quote, but it's escaped, continue looking for another quote
-found another quote
-assign everything from first quote to last quote ('hi my name\'s Parham') to the variable $phrase
-found semi-colon, this line is done with, can now move onto the next line (the semicolon tells PHP when to move onto the next command (usually on the next line).

Hopefully you're following everything well, I've tried to keep everything as simple and clear as possible.  Please don't hesitate to post questions.

The next thing we'll discuss is variable interpolation.  The word "interpolation" means to insert or introduce between other elements or parts.  Variable interpolation therefore means to use one variable inside another.  Let us for example declare two variables:


$name = 'Parham';
$age = '19';


To use these two variables and declare a whole new third variable I'd do this:


$phrase = "$name is $age years old";


Note the use of double quotes.  Doubles quotes and single quotes have very different meanings when it comes to declaring variables.  Single quotes take everything literally, meaning no variables are ever interpolated whereas double quotes interpolate variables:


$phrase1 = '$name is $age years old'; //this would literally be assigned to $phrase

$phrase2 = "$name is $age years old"; //this would find the values of $name and $phrase and stick them in


print() and echo() are two PHP language constructs which allow you to output information to the user.  It is best to demonstrate these two functions without giving too much explanation.  Here is an example that will not only show you everything we've learned about variables above, but it will also show you examples of the print() and echo() functions:


<?

$name = 'John';
$age = '19';
$location = 'Canada';

//print examples
print('Hello'); //outputs "Hello" to the user
print 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
print 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                               //this will print "Hello how are you?"

//-----------------------------------------------

//echo examples
echo('Hello'); //outputs "Hello" to the user
echo 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
echo 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                              //this will print "Hello how are you?"
echo 'Hello',' how are you?'; //the "," can also be used with echo() to output a string
                              //this will print "Hello how are you?"

//-----------------------------------------------

//print with variables
print $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//echo with variables
echo $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

echo $name , ' is ' , $age , ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//print and echo with variable interpolation
print "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

echo "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

?>


It is also worth mentioning that you only need to escape characters that you use to surround the entire variable's value with.  For example:


print "I said \"hi\""; //need to escape the double quotes around "hi"
print 'I said "hi"'; //don't need to escape the double quotes around "hi"
print "I said 'hi'"; //don't need to escape the single quotes around 'hi'
print 'I said \'hi\''; //need to escape the single quotes around 'hi'


There are speed differences between single quotes and double quotes and also between the echo() function and the print() option.  First you should know that using concatenation operators (".") with print() and (",") with echo() is MUCH faster than interpolating and letting PHP figure out where the variables are.  You should also note that echo() is slightly faster than print() because print returns a "true" value (in the form of "1") to tell you it has printed.

For more information, please read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Shadow

In your examples (such as the one below) why do you put the spaces before and after the quotes and dots?
echo $name . ' is ' . $age . ' and lives in ' . $location;
Just do it, go Charter! [Unknown] offered me a spot on the dev team! I swear it!

"Sup foos'! I'm Marshie! Capital M and then arshie! I'm going this way!!!"

[Unknown]

Because it's much easier to read.Whydoyouputspacesaroundwords,andwhydoyouputspacesaroundpunctuation?

-[Unknown]

Shadow

I believe the following is just as easy to read.
echo $name.' is '.$age.' and lives in '.$location;
Just do it, go Charter! [Unknown] offered me a spot on the dev team! I swear it!

"Sup foos'! I'm Marshie! Capital M and then arshie! I'm going this way!!!"

Parham

Well all have our own styles, I choose to put spaces because it helps me see it better.  You can, if you want, not put the dots.  Completely up to you :)

Iridium

#5
Quote from: Parham on August 27, 2003, 08:50:55 PM
There are speed differences between single quotes and double quotes and also between the echo() function and the print() option.  First you should know that using concatenation operators (".") with print() and (",") with echo() is MUCH faster than interpolating and letting PHP figure out where the variables are.  You should also note that echo() is slightly faster than print() because print returns a "true" value (in the form of "1") to tell you it has printed.

The sections I have italicized above are unfortunately, false.

Whilst there may be a speed difference during the parsing phase of the script's execution, once that is completed, there is absolutely no difference whatsoever between:

print "something"
and
print 'something'

Also, echo and print are both equally fast (and I'm not talking "almost the same" I'm talking indistinguishable).

Also I think it would be wise to point out that as far as interpolation and concatenation go, although concatenation is a few times faster than interpolation, it's worth pointing out that the difference in the number of seconds it takes per print/echo is in less than 0.0001s. This minute period of time is dwarfed by other factors such as transferring the data to the client.

[Unknown]

Not true at all.  My benchmarks have shown that single quotes, when used correctly, are MUCH faster than double.

It's important to note that not many people do it they way I mean by "correctly".  Here:

Wrong: echo 'Hello ' . $name;
Wrong: print 'Hello ' . $name;
Wrong: echo "Hello $name";
Wrong: print "Hello $name";

Between those four, there is hardly any difference - I will agree.  There IS a difference, and it is important, but it's not big enough to worry about in most cases.  HOWEVER, there's another way - the right way - which is a lot faster, and is a lot better.  (tested in PHP 4 and 5.)

echo 'Hello ', $name;

This is faster than interpolation AND faster than concatenation.  It also can be used to output numbers, and the like, with NO DATA CONVERSION.  This is also significantly faster.

And, while it may be only .0001s, think about what you just said.  Let's say I output data with if's, etc. in... say, SMF.  So, eventually we'll have at least around 20 or 30 echo/print's with single/double/interpolated/etc. quotes.

.0001 (nothing) * 25 = .0025 (not nothing.)

Now, let's say we have... 10 users online (which isn't too much.) and there are 3 who are actively clicking at approximately the same time...

.0025 * 3 = .0075.

Now, look at the load time.  Say it's .054.  You do realize that the difference you just shrugged off could account for more than 5% of that?  Maybe you think 5% is not a lot - I certainly don't agree.

-[Unknown]

Aquilo

using echo-comma has also helped me allot in my new zodiac installer, I was looking for was to get true:false statements into an echo line and the commas where the only way to get it done, meaning I didn't have to stop the echo pare an if statement then start back echo.

<?php
echo   "\n", '<BR /><BR />', "\n",
   ($color == 'r') ? '<font color="#FF0000">' : '<font color="#008000">',
   '<b>ERROR Number ', $j '</b></font>:<BR />', "\n",
   ($i != 'db') ?
   '&nbsp;&nbsp;&nbsp;$sql[', $i '] was unsuccesfull in installing '
   : '<b>* ';
?>

I did find an old but still very usefully bench-mark script at YaBB SE that showed echo-comma
is faster.

Test #0 (echo-comma) was the fastest at 0.05 seconds.
Test #1 (echo-single) came in with 0.059 seconds.
Test #2 (print-single) came in with 0.06 seconds.
Test #3 (heredoc) came in with 0.082 seconds.
Test #4 (echo-double) came in with 0.084 seconds.
Test #5 (print-double) came in with 0.084 seconds.


The one thing I have never asked about is whether switching from double-quotes to single-quotes just to get new line \n and tab \t is a good thing!?

but if using echo-comma is the right way to do this then I'm going to use it all the time not just for when I need to have a true:false statement in it!

[Unknown]

Switching is best avoided.  You get a penalty for starting a new string, so if you just make it longer it's not too bad.

"\n", '<BR /><BR />', "\n",

Might be better as:

"\n<br /><br />\n",

-[Unknown]

Parham

do what i do.. herdoc all your information out :D

[Unknown]

Quote from: Parham on September 15, 2003, 10:58:37 PM
do what i do.. herdoc all your information out :D

That is the absolute slowest method in PHP 4, and still quite slow in PHP 5.

-[Unknown]

Parham

It is very easy to read though (I'm not saying I do it with everything).  I think my efforts are better wasted on things like database optimization, serious code optimization (with good algorithms), and security issues :)

Aquilo

and awesome Tutorials on the side.  ;D
can't what for the more technical stuff! :D
like using socket_create to make a IRC bots that
can ping the crap out of everyone on it...
  :o just joking! ;D

Spaceman-Spiff

i like using heredoc on a piece of code that contains html and javascript
so i dont need to escape the quotes or single quotes :P
but i try to avoid it...

Martje

Quote from: Parham on September 15, 2003, 10:58:37 PM
do what i do.. herdoc all your information out :D

what is heredoc?  ;) or is that a stupid question in lesson 4?

[Unknown]

Heredoc:

print <<<EOT
<p>Test: "$variable"</p>
EOT;


It interpolates, but you don't have to escape quotes... only $'s.  Very slow.

-[Unknown]

Parham

Quote from: [Unknown] on October 21, 2003, 08:44:46 PM
Heredoc:

print <<<EOT
<p>Test: "$variable"</p>
EOT;


It interpolates, but you don't have to escape quotes... only $'s.  Very slow.

-[Unknown]

relatively slow to the other types of printing (which are all pretty fast), but VERY convenient.

writeto

Since I am bored and love to spread my opinion:

herdoc should be used on in the instance when not using it make your code unintelligible. That is if attempting to follow what is going on, for instance in a on the fly generated javascript, becomes a nightmare I will do it.

Other then that there is never a reason to do something that will inhibit the performance of your application/script. The only reason I find this to be acceptable is because there will come a time when you will have to go back and review what you did. This becomes a nightmare if you can't follow what is going on, and no matter how well you comment your code it just isn't always enough.


woolef

I have a question;

When you see php code in files why do some lines start on the left and some are inset? Ie;

while ($data = mysql_fetch_array($request))
{
                     echo $data['string'], ' ', $data['name'], '<br />';
}


Why isn't the 'echo' line set to the left as the brackets are? Is this a personal preference thing?

Cheers
Woolef

Parham

That's 100% preference... the PHP compiler sees it all the same.  When coding, people have their own personal preferences about how they indent code to make it easier to read.  I personally prefer two spaces for every new scope (every new set of curly brackets), others prefer spaces, and like the code you posted, others prefer that many spaces.

Advertisement: