In this third post in the PHP series, we'll dive into how PHP variables work. Variables are containers for temporarily storing values. The values stored in PHP variables could be any of the following:
I'll go into detail about each of those datatypes in future posts. No matter what kind of value will be stored in a PHP variable, they will always follow some simple rules:
Here's an example of a PHP variable:
1
2
$firstName = "Miles";
echo"$firstName";
This outputs the string "Miles" to the web page.
Now that you know the basics of PHP variables, let's create a new file called program2.php starting off with the familiar template from before.
1
2
3
4
5
6
7
8
9
10
11
12
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8">
<title>PHP Program 2</title>
</head>
<body>
<?php
?>
</body>
</html>
Between the php tags, we'll make three variables, $song, $album, and $artist. These variables can contain whatever data you wish.
1
2
3
4
5
<?php
$song = "Epidermis";
$album = "Chocolate Wheelchair";
$artist = "Venetian Snares";
?>
Now that we've defined these three variables, let's echo them out into an actual sentance.
1
2
3
4
5
6
<?php
$song = "Epidermis";
$album = "Chocolate Wheelchair";
$artist = "Venetian Snares";
echo"<p>The song <em>$song</em> is on the album \"$album\" by $artist</p>"
?>
PHP makes this easy because you can just throw variable names right in the middle of a string. Many other languages make you end the string before concatenating the variable to it, and then concatenating the rest of the string. Speaking of concatenating, lets go into how that works in PHP.
That pretty much sums it up. Concatenation is where you add characters to the end of a string. PHP even allows you to concatinate numbers, while some other languages do not. You do this using the concatenation operator, which is just a period (.) as an example, make a new line under the last echo statement and define the following variables.
1
2
3
4
5
6
<?php
$title = "Dr.";
$firstName = "Michio ";
$lastName = "Kaku";
$fullName = $title . $firstName . $lastName;
?>
The variable $fullName now holds the value "Dr.MichioKaku", which is not really what we want. We'll need to concatenate spaces between each of the three variables.
1
2
3
4
5
6
<?php
$title = "Dr.";
$firstName = "Michio";
$lastName = "Kaku";
$fullName = $title . ' ' . $firstName . ' ' . $lastName;
?>
Now the variable $fullName holds the value "Dr. Michio Kaku", which is exactly what we would expect. Keep in mind that none of this concatination will be noticeable to the user. Even if they look at the source code, they would just see standard HTML. This is an excellent way to make the HTML content of web pages dynamically generated by your PHP program. This will be much more useful later on in this series.
Now that we've gone over variables, strings, and concatination, the next post will be about numbers and math operators!
Special thanks to Larry Ullman, whose textbooks helped me learn PHP programming (no affiliation)