PHP Tutorial
This page is a small tutorial on how to use the PHP Programming language. It’s not meant as a sole repository for learning how to write PHP programs.
History & Background ↓
This sections describes the history and evolution of the PHP programming language.
Today PHP is a recursive acronym for PHP: Hypertext Preprocessor. In 1995, it stood for Personal Home Page and named a bunch of utilities that evolved from some Perl scripts. It was originally developed to display the résumé of Rasmus Lerdorf. He developed the original PHP.
PHP is a weakly typed language, although some prefer to label it a dynamically typed language. It has similar syntax to Perl in many respects, including variables preceded by dollar signs – $sample_variable
. PHP is also a server-side include type of programming environment. As such, you may deploy it as a CGI or Apache module. It is also an interpreted rather than compiled programming language.
The language is flexible in two important ways: It is tightly integrated with HTML, and it has the ability to work with virtually all databases. The language enables you to embed PHP in an HTML document and to embed HTML inside a PHP script. You can also use PHP from the command-line, as a server-side scripting language. However, it has limited I/O characteristics reading and writing files.
The downside of PHP from the perspective of its critics has three points. PHP has a single name space for functions, it isn’t thread safe, and as mentioned it is a weakly typed language. Perl takes a hit from the same critics.
Writing your first page ↓
This sections describes the scripting tags, comments, and printing output to your web page from a PHP program and from an HTML page.
Tags
There are four tag styles available. Only two are automatically configured for you when you install the Zend Community Server. They are the default and HTML-style tags. You’ll have to look elsewhere for the short-style and ASP-style because they’re not a great choice.
<?php print "Hello world.<br />"; ?> |
HTML-Style
<script language="php"> print "Hello world.<br />"; </script> |
Comments
PHP supports three types of comments. Two are single line comments and one is for multiple line comments. They’re shown below and the comments describe their comment type.
<?php // A single-line comment style and recommended style. # A single-line comment style but easily confused with operating systems scripts. /* A multiple line column, and recommended style. This is the second line, as you can see. */ ?> |
Printing Output
PHP supports several means of writing output to the web page but these two are the most frequently used. It really doesn’t matter which one you choose because they perform equally. You should pick one and use it consistently.
<?php // This prints or echos to the web page. print "Hello World."; // This prints or echos to the web page. echo "Hello World."; ?> |
First Page
This is a HTML page with embedded PHP.
1 2 3 4 5 6 7 8 | <html> <body> <?php // This prints or echos to the web page. print "Hello World."; ?> </body> </html> |
This is a PHP page with embedded HTML.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // Print opening tags. print "<html>"; print "<body>"; // This prints or echos to the web page. print "Hello World."; // Print closing tags. print "</body>"; print "</html>"; ?> |
Command Line Scripting
You can also write PHP programs to run from the command line. This shows you how to write a page when you want to run it from the command line interface.
Most of the sample programs in this tutorial do exactly that to simplify testing the PHP sample programs. It eliminates the web browser and Zend Community Server components.
The only change required to the previous example is changing the “<br />” to a “\n”. The “\n” is a line break when run at the command line. You can see it in the following program.
<?php print "Hello world.\n>"; ?> |
Assuming you named the program Hello.php
, you would call it from the command line as follows:
php Hello.php |
Variable Definition, Declaration, & Assignment ↓
This sections describes how to define, declare, and assign values to variables.
As a weakly typed language, PHP requires careful attention to how you define, declare, and assign values. The assignment is the greatest risk because a PHP variable implicitly inherits their type from an assignment, and the data type of a PHP variable can change during program run time.
You create a variable by assigning it a name, which is also known as an identifier or token. The identifier becomes part of the run time program, and a unique value in the name space of the program. The name space is a list of all variables and their data types.
Defining Variables ↓
This sections describes how you define variables.
You can define a variable by using any series of case-sensitive alphabetical characters, numbers, or underscores, but they must start with an alphabetical character or underscore. Variables are identified by prefacing the name with a $
(dollar) symbol.
The following are valid variable names:
1 2 3 4 5 6 7 | <?php // Defining variables. $_MIGHTY; $_1toMany; $mightyMouse; $mighty1cool; ?> |
Some would say a variable is defined in PHP without a data type but it actually is a null data type. Null is a special data type in PHP. The fact that all defined variables have a null data type is the reason some call PHP a dynamically typed language not a loosely typed language. However, if you were to look beneath the hood you’d find that this is a void
data type, which makes it loosely typed.
You can prove this to yourself by running the following program from the command line in a shell environment. It’s easier to test that way because you remove the browser from the equation.
1 2 3 4 | <?php // Displaying the data type of a defined variables. print gettype($nada)."\n"; ?> |
The gettype()
function returns the data type of a variable. While $nada
doesn’t appear to be declared before it is provided as a call parameter to the function, it is declared with its first use in the program. Since it hasn’t been assigned a value, it’s contains nothing, which is treated as a null value.
Assuming you save the program above as a defined_type.php
file, you can see the results by running it from the command line, like the following.
php defined_type.php |
It’ll prints the following:
NULL |
Declaring Variables ↓
This sections describes how you declare variables.
You can declare a variable by defining it and assigning it a value, or you can declare a variable and initialize an object of a data type. In either case, declaration means that the variable has a name, data type, and potentially a value. If you initialize an empty array()
object, the value would be an empty set.
The =
(equals) symbol is the binary assignment operator that takes the value and type of the variable or literal value on the right (known as the right operand) and assigns it to the variable on the left (the left operand). Once you’ve assigned a value, a variable is declared. It’s data type however, is still changeable. A second assignment of another variable may change the type and have unanticipated results when you fail to understand this rule.
Here’s a quick example on declaration, and subsequent assignment operations. It uses the increment and assign and concatenate and assign operators (covered in the Assignment fold out.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // Declaring a variable and print contents. $demo = 10; print "Value [$demo] Data type [".gettype($demo)."]\n"; // Concatenation and assign to a variable and print contents. $demo .= 1; print "Value [$demo] Data type [".gettype($demo)."]\n"; // Concatenation and assign to a variable and print contents. $demo += 1; print "Value [$demo] Data type [".gettype($demo)."]\n"; ?> |
The initial declaration assigns a numeric literal value to the $demo
variable, which makes the variable’s data type an integer
. A subsequent concatenate and assign operator is more complex.>
The rationale for this is two fold. First, it assumes the right operand must be a string. It casts the numeric literal to a string and glues it at end of the present value, making it a string of 11. The increment and assign operator assumes the right operand is a number and implicitly casts the left operand to a number before adding the two values.
The dynamic typing capability of PHP provides for value comparison and value and type comparison (known as identity comparison), as you’ll see later in the tutorial. It’s important that you take note of this for the identity comparison discussion.
The output from the program is:
Value [1] Data type [integer] Value [11] Data type [string] Value [12] Data type [integer] |
The variables you’ve seen so far are scalar variables, which means they can hold only one thing. That thing can be a number, date, string, null, or reference to a resource or object. Arrays and objects are complex and covered in their own sections. However, you’ll need to know a bit about arrays here to support the discussion on loops.
You declare an empty array like the following example. The sample program declares a $sampleArray
variable that initially holds an empty array. After declaring the $sampleArray
variable, you assign values to elements of the array. The first two use index values of 0
and 1
, while the last uses an unnumbered index. When you use numeric indexes, they don’t require explicit assignment of values. PHP automatically assumes you want the last index value plus one.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // Defining an empty array. $sampleArray = Array(); // Assign it some values one at a time. $sampleArray[0] = 'One'; $sampleArray[1] = 'Two'; $sampleArray[] = 'Three'; // Print the contents of the empty Array. print_r($sampleArray); ?> |
You can also initialize the array by declaring it with a series of values (implicitly assigning them by numeric indexes), like this:
1 2 3 4 5 6 7 | <?php // Defining an empty array. $sampleArray = Array('One','Two','Three'); // Print the contents of the empty Array. print_r($sampleArray); ?> |
The print_r()
function lets you see the contents of either of these arrays. You would see the following if this code were run from the command line.
1 2 3 4 5 6 | Array ( [0] => One [1] => Two [2] => Three ) |
A string index differs from the prior examples. You must always provide the index explicitly. The next example mimic the declaration and subsequent assignment of string indexed values to an array.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // Defining an empty array. $sampleArray = Array(); // Assign it some values one at a time. $sampleArray['First'] = 'One'; $sampleArray['Second'] = 'Two'; $sampleArray['Third'] = 'Three'; // Print the contents of the empty Array. print_r($sampleArray); ?> |
You can also initialize the array by declaring it with a series of values indexed by strings, like this:
1 2 3 4 5 6 7 | <?php // Defining an empty array. $sampleArray = Array('First'=>'One','Second'=>'Two','Third'=>'Three'); // Print the contents of the empty Array. print_r($sampleArray); ?> |
As shown with numeric indexes, the print_r()
function lets you see the contents of arrays. You would see the following if this code were run from the command line.
Array ( [First] => One [Second] => Two [Third] => Three ) |
As noted, both print the same output. These examples This should be enough to support the array-based examples for loops. There’s much more to understand about arrays but you’ll see that in a later part of the tutorial.
You also have Variable variables. These are variables that let you layer variable names. This shows you how they work with a variable that holds an array.
1 2 3 4 5 6 7 8 9 10 11 | <?php <?php // Defining an empty array. $sample = "sampleArray"; // Assign the array to value of the $sample variable. $$sample = Array('First'=>'One','Second'=>'Two','Third'=>'Three'); // Print the array. print_r($sampleArray); ?> |
You would see the same results as earlier for a string indexed array. The difference is that the $$sample
and $sampleArray
hold the same value.
Assignment Operators ↓
This sections describes supported assignment operators.
The following list assignment operators and their roles in the language.
Assignment Operators | |
---|---|
Operator | Description |
= | The assignment, = (equals), operator is a binary operator. It takes the right operand value to the left operand variable. The left operand variable implicitly inherits the data type from the right operand when they’re not the same data type. |
+= | The increment and assign, += (add and assign), operator is a binary operator. It takes the right operand value and adds it to the left operand variable. It also assigns the data type of the right operand to the left operand variable when the data type is more precise. For example, when you add and assign a 1.2 value to an int , the variable becomes a double data type. |
-= | The decrement and assign, -= (subtract and assign), operator is a binary operator. It takes the right operand value and subtracts it from the left operand variable. It also assigns the data type of the right operand to the left operand variable when the data type is more precise. For example, when you subtract and assign a 1.2 value from an int , the variable becomes a double data type. |
*= | The multiply and assign, *= (multiply and assign), operator is a binary operator. It takes the left operand value and multiplies it by the right operand variable before assigning it to the left operand. It also assign the data type of the right operand to the left operand variable when the data type is more precise. For example, when you assign a fractional value to an int , the variable becomes a double data type. |
/= | The divide and assign, /= (divide and assign), operator is a binary operator. It takes the left operand value and divides it by the right operand variable before assigning it to the left operand. It also assign the data type of the right operand to the left operand variable when the data type is more precise. For example, when you assign a 1.2 value to an int , the variable becomes a double data type. |
.= | The concatenate and assign, .= (divide and assign), operator is a binary operator. It appends the right operand value to the left operand variable’s value. It also converts a right operand to a string before appending it to the right operand. When the right operand is a numeric value, the appending of a string converts the number to a string data type. |
–– | The decrement, -- (decrement by one), operator is a unary operator. It subtracts 1 from the value of the variable. It subtracts the value before an operation (--$var; ) when it precedes the variable, and after an operation ($var--; ) when it follows the variable.
|
++ | The increment, ++ (increment by one), operator is a unary operator. It adds 1 to the value of the variable. It adds the value before an operation (++$var; ) when it precedes the variable, and after an operation ($var++; ) when it follows the variable.
|
Globals, Predefined Variables, and Includes ↓
This sections describes global variables, predefined variables, and how to include libraries.
Global Variables
Global variables in PHP are global to the executing script. Therefore, you may only place one copy in memory during an execution cycle.
There’s only one way to create a global variable in PHP. You use the define()
function. They’re named and called without the $
symbol used by other variables. PHP global variables act as constants and don’t change during program run-time. By convention, they’re uppercase variable names that hold strings or numbers.
<?php // Define a global variable. define('MY_GLOBAL','Enter Narnia through the wardrobe.'); // Print the global variable. print "['MY_GLOBAL'] is [".MY_GLOBAL."]\n"; ?> |
Predefined Variables
Predefined variables are also called superglobal variables. These variables are key elements of the PHP programming language. They hold server-side environment variables, HTTP GET
and POST
variables, session variables, file variables, and HTTP cookies.
Predefined variables are arrays indexed by strings. The string indexes act as labels for the variables. The table list there name and what they contain.
Comparison Operators | ||
---|---|---|
Global | Description | |
$GLOBALS | The variable contains a reference to every variable within the global scope of the script set that’s currently running. | |
$_COOKIE | The variable contains all HTTP cookies. It replaces the deprecated $HTTP_COOKIE_VARS array. |
|
$_ENV | The variable contains all inherited environment variables or those directly set within a script, script includes, or run-time included library. It replaces the deprecated $HTTP_ENV_VARS array. |
|
$_FILES | The variable contains all variables provided by the HTTP POST file uploads. It replaces the deprecated $HTTP_POST_FILES array. |
|
$_GET | The variable contains all parameters passed by the HTTP GET . This is a risky method for passing parameters and should be avoided where possible for the POST method. It replaces the deprecated $HTTP_GET_VARS array. |
|
$_POST | The variable contains all parameters passed by the HTTP POST . It replaces the deprecated $HTTP_POST_VARS array. |
|
$_REQUEST | The variable contains all parameters passed by HTTP GET , POST , and COOKIE elements. This is a risky variable to use because the $_GET parameter and $_COOKIE values are security risks because they may be tampered with easily (editing URLs). |
|
$_SERVER | The variable contains environment variables set by the execution environment of the CGI or Apache Mod PHP engine. It replaces the deprecated $HTTP_SERVER_VARS array. |
|
$_SESSION | The variable contains variables bound to the current script session. It is a place where you may include configuration variables that you want shared between browser session and the server. However, where possible you should keep this to a minimum. It replaces the deprecated $HTTP_SESSION_VARS array. |
Library Inclusion
PHP has four library file inclusion commands. They all take a single parameter, which is the path and file name of a library file. Library files may use any acceptable extension recognized in the php.ini
file, but typically they use the *.inc
file.
When the path
is excluded they assume the relative path. That means the same directory or folder when the current script is found.
They’re covered in the following table.
Comparison Operators | ||
---|---|---|
Global | Description | |
include("path/name"); |
You should only use the include() function once in any script execution. The include_once() function is generally preferred. It raises a warning message when the argument fails to resolve a correct path and file name on the server. If it’s called more than once, you can inherit the same file library twice. |
|
include_once("path/name"); |
You should only use the include_once() function once in any script execution. However, if called twice there’s no problem with your code because it checks whether the library is already loaded. It raises a warning message when the argument fails to resolve a correct path and file name on the server. |
|
require("path/name"); |
You should only use the require() function once in any script execution. The require_once() function is generally preferred. It raises a warning message when the argument fails to resolve a correct path and file name on the server. If it’s called more than once, you can inherit the same file library twice. |
|
require_once("path/name"); |
You should only use the require_once() function once in any script execution. However, if called twice there’s no problem with your code because it checks whether the library is already loaded. It raises a warning message when the argument fails to resolve a correct path and file name on the server. |
An example using the include_once()
function shows calling a credentials.inc
library file. The file contains global variables that define the database user, password, port, and database required to connect to a server-side database. Such library files are often placed in a global
library directory.
<?php // Define a global variable. include_once('global/credentials.inc'); ?> |
Reserved Words
Reserved word lists are generally close and frequently revised because modern programming languages are constantly evolving. This is the official reserved word list for PHP 5.3 at the time of writing.
Control Structures – Condition Statements ↓
This sections describes how you use if and switch statements
Definitions and Prototypes ↓
This sections describes the prototypes for conditional evaluation statements.
There are two ways to implement an if
statement. One is a traditional block structure and the other is a ternary operator. The switch
statement is a bit more complex because you can switch on a variable or expression, and you can allow, disallow partially, or disallow fully fall-through behavior.
if
statement
The if
statement prototype is noted below. It is critical that you enclose comparison variables or expressions in parentheses. You raise a compile time error when you don’t. The opening and closing curly braces are only necessary when you perform two or more statements in a block but good practice teaches you should always use them. It’s a good practice because sometimes you add a second statement later and forget them, which typically generates a run-time error.
if (expression) { statement; } else if (expression) { statement; } else { statement; } |
Ternary if
statement
The ternary if
statement prototype is noted below. It is also critical that you enclose comparison variables or expressions in parentheses. You raise a compile time error when you don’t. Curly braces are possible but typically you use a ternary operator for brief singular evaluations. As you get accustom to them, they add clarity in that context.
(expression) ? true_statement : false_statement; |
When the expression is evaluated and found true, you perform the truth statement. You should note that there’s no semicolon after the true statement in the prototype. This isn’t an error. You only put the semicolon at the end of the ternary expression.
When the expression is not true, you perform the false statement. You may also nest ternary comparisons but they become very difficult to read for maintenance programming staff. The best practice is to avoid their more complex use unless the cost of maintenance programming is irrelevant.
switch
statement
The switch
statement prototype is noted below with some distinct differences from earlier prototypes. It uses [ ]
(square brackets) to enclose optional elements, and a |
(pipe) to indicate this or that. After the expression
there’s a :
(colon) and a true
keyword. This indicates that if you fail to put a variable or expression, PHP automatically substitutes a true
value. This means all case
criterion (singular) or criteria (a set of Boolean expressions) work when they return true, unless you provide break;
statements. A break;
statement tells PHP to exit the switch
block immediately.
It is just as critical that you enclose comparison variables or expressions in parentheses. They occur two places in a switch
statement. They occur after the switch
keyword and the case
keyword.
It is always a good practice to provide a default
case because you want to demonstrate you expect them or can ignore them. An empty default
block says you don’t need to handle the event.
switch [(variable | expression:true)] { case (criterion | criteria): { statement; [break;] } case (criterion | criteria): { statement; [break;] } default: { statement; } |
Fall through behavior occurs when you exclude the break;
statements from case
blocks. Fall through is the process of meeting first case
block criterion or criteria and then processing all remaining case
blocks. It has very specific uses but as a rule isn’t what you plan when writing a switch
statement. break;
statements are generally the better and more common practice.
Comparison Operators ↓
This sections describes the comparison operators for conditional evaluations.
There are seven basic comparison operations. One has two varieties, which is the not equal comparison operator. They’re listed in the table below.
Comparison Operators | ||
---|---|---|
Operator | Description | |
== | The two equal signs together returns true if the values are the same regardless of data type. | |
=== | The three equal signs together returns true if the values and the data types are the same. | |
!= | The exclamation (or bang) operator and an equal sign or the less-than and greater-than symbols together return true if the values are different regardless of data type. | |
<> | ||
< | The less-than sign returns true if the left operand values is less than the right operand value. | |
> | The greater-than sign returns true if the right operand values is greater than the left operand value. | |
<= | The less-than or equal sign returns true if the left operand values is less than or equal to the right operand value. | |
>= | The greater-than or equal sign returns true if the right operand values is greater than or equal to the left operand value. |
Conditional Statement Examples ↓
This section provides conditional evaluation statement examples.
Default block if
-statement ↓
The if
statement has several variations on the prototype. While these aren’t exhaustive, they should serve you well as you begin working with the PHP language.
Comparing truth by data type
Like other weakly typed programming languages, PHP supports evaluating a Boolean, or ordinary data types as true or false. This is important because you could erroneously assign a value and a data type to control variable.
Control variables typically act as logical guards to if
-statements, switch
-statements, and for
-loops. You may encounter run-time failure when they’re not Boolean data types unless you know how values are evaluated.
The following program shows you how truth is checked for single variables of different data types. A float behaves like an integer and is omitted for space.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <?php // This declares local variables. $a = true; // This is a Boolean (bool) data type for true. $b = false; // This is a Boolean (bool) data type for false. $c = "a"; // This is a full string data type. $d = ""; // This is an empty string data type. $e = 0; // This is an integer value of zero. $f = -1; // This is a negative integer value. $g = 1; // This is a positive integer value. $h = null; // This is a special null data type. // This compares a Boolean variable's truth. if ($a) { print "Variable [\$a][$a] is a [".gettype($a)."] and is true.\n"; } else { print "Variable [\$a][$a] is a [".gettype($a)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($b) { print "Variable [\$b][$b] is a [".gettype($b)."] and is true.\n"; } else { print "Variable [\$b][$b] is a [".gettype($b)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($c) { print "Variable [\$c][$c] is a [".gettype($c)."] and is true.\n"; } else { print "Variable [\$c][$c] is a [".gettype($c)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($d) { print "Variable [\$d][$d] is a [".gettype($d)."] and is true.\n"; } else { print "Variable [\$d][$d] is a [".gettype($d)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($e) { print "Variable [\$e][$e] is a [".gettype($e)."] and is true.\n"; } else { print "Variable [\$e][$e] is a [".gettype($e)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($f) { print "Variable [\$f][$f] is a [".gettype($f)."] and is true.\n"; } else { print "Variable [\$f][$f] is a [".gettype($f)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($g) { print "Variable [\$g][$g] is a [".gettype($g)."] and is true.\n"; } else { print "Variable [\$g][$g] is a [".gettype($g)."] and is false.\n"; } // This compares a Boolean variable's truth. if ($h) { print "Variable [\$h][$h] is a [".gettype($h)."] and is true.\n"; } else { print "Variable [\$h][$h] is a [".gettype($h)."] and is false.\n"; } ?> |
When you run this program from the command line, it prints the following results:
Variable [$a][1] is a [boolean] and is true. Variable [$b][] is a [boolean] and is false. Variable [$c][a] is a [string] and is true. Variable [$d][] is a [string] and is false. Variable [$e][0] is a [integer] and is false. Variable [$f][-1] is a [integer] and is true. Variable [$g][1] is a [integer] and is true. Variable [$h][] is a [NULL] and is false. |
As you’ll notice in the output, a Boolean returns 1
when true and null
when false. Likewise, a string of anything is true and a null isn’t, and a number other than zero is true while 0
is false. The special null data type is always false.
Comparing truth of multiple things
Sometimes you need to evaluate whether two variables or expressions are true in a single if
-statement, or whether at least one is true. In less frequent situations, you need to check if only one of two or more variables or expressions are true.
You have a number of logical operators that support the conditional evaluation of two or more variables or expressions. The following table highlights the logical operators.
Logical Operators | |
---|---|
Operator | Description |
and | The text operator checks for the combined results of two comparisons. |
&& | The symbol operator checks for the combined results of two comparisons. |
or | The text operator checks for the results of at least one comparative operation. |
|| | The symbol operator checks for the results of at least one comparative operation. |
xor | The exclusive or operator checks for the results of only one comparative operation among a set of comparisons. |
! | The bang operator negates the state of a variable or expression. |
The examples here demonstrate three types of evaluation. The first example checks whether two variables are true.
1 2 3 4 5 6 7 8 9 10 11 | <?php // This declares local variables. $a = true; $b = true; // This compares two values. if ($a && $b) { print "Variable [\$a] and [\$b] are both true.\n"; } else { print "Variable [\$a] and [\$b] aren't both true.\n"; } ?> |
Since we used Boolean variables and set them to true, their combination is also true. If we change $a
or $b
to false, then the combined evaluation would return false and print a message saying that they both aren’t true. As it is, the program prints the following:
Variable [$a] and [$b] are both true. |
The next example demonstrates when one or the other variables is true, or coincidentally both are true. This type of evaluation stops when it finds one true. This is short circuit truth evaluation.
1 2 3 4 5 6 7 8 9 10 11 | <?php // This declares local variables. $a = true; $b = false; // This compares two values. if ($a || $b) { print "At least variable [\$a] or [\$b] is true.\n"; } else { print "Neither variable [\$a] or [\$b] are true.\n"; } ?> |
It would print:
At least variable [$a] or [$b] is true. |
Sometimes, we need to know whether $a
is true when $b
is false or vice versa. This is known as an exclusive or situation. You can change the operator but you’ll also need to add an elseif
to capture when both are true.
This example program shows that logic:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // This declares local variables. $a = true; $b = false; // This compares two values. if ($a || $b) { print "At least variable [\$a] or [\$b] is true.\n"; } if ($a && $b) { print "Both variable [\$a] or [\$b] are true.\n"; } else { print "Neither variable [\$a] or [\$b] are true.\n"; } ?> |
With one true and false variable the first message is printed.
At least variable [$a] or [$b] is true. |
Comparing values of the same data type
Like earlier examples, these are designed to run from the command line. If you want them to work in a browser, change the \n
to a <br />
in the code. The example compares matching and non-matching values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php // This declares local variables. $a = "One"; $b = "One"; $c = "Two"; // This compares the values. if ($a == $b) { print "Variable [$a] matches variable [$b]"; } else { print "Variable [$a] doesn't match variable [$b]"; } // This compares the values. if ($a == $c) { print "Variable [$a] matches variable [$c]"; } else { print "Variable [$a] doesn't match variable [$c]"; } ?> |
This prints the following:
Variable [One] matches variable [One] Variable [One] doesn't match variable [Two] |
Comparing values of different data type
Like earlier examples, these are designed to run from the command line. If you want them to work in a browser, change the \n
to a <br />
in the code. The example compares matching and non-matching values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php // This declares local variables. $a = 1; $b = 1; $c = "1"; // This compares values of the same data type. if ($a === $b) { print "Variable [$a] matches variable [$b]\n"; } else { print "Variable [$a] doesn't match variable [$b]\n"; } // This compares values of different data types. if ($a === $c) { print "Variable [$a] matches variable [$c]\n"; } else { print "Variable [$a] doesn't match variable [$c]\n"; } ?> |
This prints that the numeric value of 1 equals another numeric value of 1. It also shows that a numeric value of 1 doesn’t equal the string equivalent. These checks use the ===
(identity) comparison operator.
Variable [1] matches variable [1] Variable [1] doesn't match variable [1] |
You could explicitly cast the string of 1 to an integer before making the comparison. That change to line 15 would be:
14 | if ($a === (int) $c) { |
The change would result in text string that says $a
is identical to $b
. Identical in this case means the two variables hold the same variable value and data type.
Ternary if
-statement ↓
The ternary if
statement best use is for a single evaluation. That is not always the case in practice because you can nest ternary if
-statements. This section demonstrates both a single evaluation and nested evaluation.
Single ternary comparison
A single ternary operator is fairly clear, as you can see in this example.
14 15 16 17 18 19 20 21 22 | <?php // Declare two Boolean variables. $a = true; $b = false; // Compare and process truth or falsity. ($a) ? print "Variable [\$a] is true.\n" : print "Variable [\$a] is false.\n"; ($b) ? print "Variable [\$b] is true.\n" : print "Variable [\$b] is false.\n"; ?> |
You should note that there isn’t a semicolon after the true statement, only at the end of the complete ternary statement. It prints the following.
Variable [$a] is true. Variable [$b] is false. |
A single ternary conditional evaluation is clean and readable. These are the more frequently written statements.
Nested ternary comparison
A nested ternary operator is a bit difficult to read, as you can see in this example.
14 15 16 17 18 19 20 21 | <?php // Declare two variables. $a = true; $b = false; // Evaluate truth at multiple levels in a nested ternary operator. ($a) ? ($b) ? print "Variableis [\$a] and [\$b] are true.\n" : print "Variable [\$a] is true and [\$b] is false.\n" : print "Variable [\$a] and [\$b] are false.\n"; ?> |
A white-space formatted version would look like this:
14 15 16 17 18 19 20 21 22 23 | <?php $a = true; $b = false; ($a) ? ($b) ? print "Variableis [\$a] and [\$b] are true.\n" : print "Variable [\$a] is true and [\$b] is false.\n" : print "Variable [\$a] and [\$b] are false.\n"; ?> |
The result for either of the nested statements is the same. $a
is true and $b
is false, which yields the nested else block.
Variable [$a] is true and [$b] is false. |
There’s no real best practice when it comes to how you use ternary operators but the more complex the more tedious to support.
switch
Statement ↓
The switch
statement best lets you evaluate a list of possible outcomes. It is a good fit when you have fewer than 10 possibilities. More than 10 possibilities would indicate a switch
statement may not be the best answer to your problem.
switch
on a variable value
You can create a switch statement on an integer, float, or string variable. All have a similar approach to the one below. You would simply dispense with the double quotes when using an integer or float because they’re not required.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php // Run script from command line. if (@$_SERVER["argv"]) { if ($_SERVER["argc"] > 1 ) { $salutation = $_SERVER["argv"][1]; print "Query [$salutation]\n"; }} // Write a salutation switch statement. switch ($salutation) { case "Hello": print "Response [Hello User.]\n"; break; case "Ciao": print "Response [Ciao Consumatore.]\n"; break; default: print "Unknown Language.\n"; } ?> |
When you call this program with a Hello
string the program responds in English. A call in Italian is responded in that language. Any other language replies Unknown Language.
Assuming you named the program Hello.php
, you would call it from the command line as follows:
php Hello.php Ciao |
Below is the output exchange in Italian.
Query [Ciao] Response [Ciao Consumatore.] |
The command line call can also be handled by using the getopt()
function call into an array.
switch
on an expression value
An expression value is true (by default) or false. Like the if
-statement, you may use compound comparisons in any given case
criteria. A little number guessing game illustrates the concept.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php // Declare the magic number. $magic = 48; // Run script from command line. if (@$_SERVER["argv"]) { if ($_SERVER["argc"] > 1 ) { $guess = $_SERVER["argv"][1]; print "Guess [$guess]\n"; }} // Ternary evaluation of input. (is_numeric($guess)) ? $guess = (int) $guess : $guess = 0; // Write a salutation switch statement. switch (true) { case (($guess >= 1) && ($guess <= 100)) && ($magic > $guess): print "Response [Low guess.]\n"; break; case (($guess >= 1) && ($guess <= 100)) && ($magic < $guess): print "Response [High guess.]\n"; break; case (($guess >= 1) && ($guess <= 100)) && ($magic == $guess): print "Response [Right guess.]\n"; break; default: print "Response [Illegal guess.]\n"; } ?> |
You could introduce an awesome problem if you misunderstand the purpose of a switch
statement. For example, if you changed line 15 in the preceding program as noted below, zero would always generate a “low guess” answer when it should tell you it’s an “illegal guess”. That behavior isn’t a bug. It’s the result of a two issues with a weakly typed language.
14 15 16 17 18 19 | <?php // Write a salutation switch statement. switch ($guess) { case (($guess >= 1) && ($guess <= 100)) && ($magic > $guess): print "Response [Low guess.]\n"; break; |
The $guess
is zero when you enter a none numeric call parameter or a zero. This switch
statement is actually equivalent to checking for the first false expression because a zero is equivalent to a Boolean false for a string. Therefore, it would always print the result from the first case
because a $guess
of zero is outside the acceptable range – between 1 and 100.
There’s no real best practice when it comes to how case
statements can be used in a switch
statement. You should remember that too many makes it too complex and more tedious to support. You should also guard against inadvertent type casting errors as discussed.
Control Structures – Iterative Statements ↓
This sections describes the loop structures.
for
loops
This demonstrates a simple for
loop.
<?php // Countries of Great Britain. $countries = array('England','Ireland','Scotland','Wales'); // Read through and print the countries of Great Britain. for ($i = 0; $i < count($countries); $i++) { print $countries[$i]."\n"; } ?> |
It prints the countries in the same order that they appear in the array.
England Ireland Scotland Wales |
do
–while
loop
This demonstrates a simple do
–while
loop.
<?php // Countries of Great Britain. $countries = array('England','Ireland','Scotland','Wales'); // Control variable. $counter = 0; $maximum = count($countries); // Read through and print the countries of Great Britain. do { // Print output. print $countries[$counter++]."\n"; } while ($counter < $maximum); ?> |
It prints the countries in the same order that they appear in the array.
England Ireland Scotland Wales |
while
loop
This demonstrates a simple while
loop.
<?php // Countries of Great Britain. $countries = array('England','Ireland','Scotland','Wales'); // Control variable. $counter = 0; $maximum = count($countries); // Read through and print the countries of Great Britain. while ($counter < $maximum) { // Print output. print $countries[$counter++]."\n"; } ?> |
It prints the countries in the same order that they appear in the array.
England Ireland Scotland Wales |
foreach
loop
This demonstrates a simple foreach
loop.
<?php // Countries of Great Britain. $countries = array('England','Ireland','Scotland','Wales'); // Read through and print the countries of Great Britain. foreach ($countries as $indexName => $elementValue) { // Print output. print "[\$indexName][$indexName] => [\$elementValue][$elementValue]\n"; } ?> |
It prints the index values and countries in the same order that they appear in the array.
[$indexName][0] => [$elementValue][England] [$indexName][1] => [$elementValue][Ireland] [$indexName][2] => [$elementValue][Scotland] [$indexName][3] => [$elementValue][Wales] |