Make your own free website on Tripod.com

Visit the Official PHP Website
Search this Site

PHP Programming

By James N Hitz

String Variables

Let's jog your memory:

"a variable is a named memory location which can be assigned a value"

We said this (or something close to this) in our previous discussion of variables. A variable therefore contains only one value. If this value is enclosed in double quotes it is a "string". Therefore if you had the following code snippet:

$myname="James";
$myname="Hitz";

The value of $myname at the end of the code execution is going to be Hitz. This is because by assigning a different value to an existing variable, you erase the previously stored value and replace it with the new one.

What if you wanted to add 'James' to 'Hitz' to get 'James Hitz'? Enter concatenation to the Rescure.

String Concatenation

String Concatenation means combining two or more string to get one compound string. Look at this:

$FirstName="James";
$LastName="Hitz";
$fullName=$firstName + $LastName;

It is WRONG! This is because of the mere fact that you are trying to deal mathematically with strings. $FullName now has the value'0'. Yes Zero!

"But it works in JavaScript!"

Yeah. Sorry buddy but this ain't JavaScript. In PHP, you concatenate using the dot operator (.) and not the plus operator(+). This works like this:

$firstName="James";
$lastName="Hitz";
$fullName=$firstName.$lastName;

Voila! we got it! We got it!

Shh.Did we really? This code will give us 'JamesHitz'. This is one Un-pronounable name that would cause the most eloquent broadcaster to resign! :-)

We need to add a space between the 2 names for two reasons:

  1. We wanted 2 names in the first place
  2. To save that poor guy from having to resign... <tee hee>

Solution:

$lastName = "Hitz";
$firstName = "James";
$fullName = $firstName . " " . $lastName;

This means: "$lastName is 'Hitz' and the $firstName is 'James' therefore the $fullName is 'James', plus a space (notice it is in double quotes), plus 'Hitz' to produce something more pronounable (James Hitz) and to save a Job"

Well... Thank you very much for being with me thus far. This is then end of Lesson 2 and an advent into Lesson 3. See you there!

<< phpinfo() in Action | Lesson 3 >>