Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.[php.net]
Variables are used to store strings, numbers and arrays.
$class = "Web Design";
$period = 4;
$students = array("Mary" , "Bill" , "Terry" , "Leslie" , "Joe");
$grade_asn1 = array('Mary' => 'A' , 'Bill' => 'B' , 'Terry' => 'C' , 'Leslie' => 'B' , 'Joe' => 'A');
Notes:
Let's put it all together in a short php program:
<!doctype html public "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Web Design Assignment #1 Grades </title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
$class = "Web Design";
$period = 4;
$students = array("Mary" , "Bill" , "Terry" , "Leslie" , "Joe");
$grade_asn1 = array('Mary' => 'A' , 'Bill' => 'B' , 'Terry' => 'C' , 'Leslie' => 'B' , 'Joe' => 'A');
?>
<h1><?php echo"$class"; ?></h1>
<?php
echo"<p>Period $period</p>";
echo"<p>Assignment #1 Grades</p>";
for($i=0;$i<5;$i++)
{
$student = $students[$i];
echo"<p>$student Grade $grade_asn1[$student]</p>";
}
?>
</body>
</html>
The "for" loop is used to iterate through the values in $students (student names). The "for" loop has three parameters (Initial condition, $i=0 ; Continue when True, $i<5 ; Increment the initial condition, $i++). The script contained within the curly-braces { } is executed for each cycle. In this case, the value of $i is different each time through the cycle. This results in the array $students[$i] assigning a different student name to $student each cycle. The value of $student is used as the key in $grade_asn1[$student] which contains the grade (value) associated with each student.
Here is what is displayed in the browser:
Period 4
Assignment #1 Grades
Mary Grade A
Bill Grade B
Terry Grade C
Leslie Grade B
Joe Grade A
Strings are concatenated (joined) with the dot (.). For example, if we have three string variables,
$string1 = "Alien"
$string2 = "Ant"
$string3 = "Farm"
we can join the strings, separated with spaces, into a single variable, as follows:
$string4 = $string1." ".$string2 . " " . $string3 (Note that white space on either side of the dot is ignored.)
If we echo, or print, $string4 we will see,
Alien Ant Farm
Number variables are added with the plus sign (+). For example, if we have two numeric variables,
$x = 5
$y = 2
we can add the two variables and assign the result to a new variable,
$z = $x + $y
If we echo, or print, $z we will see,
7
Operators and Control Structure