PHP source code is typically an HTML document with php
tags embedded within it:
<?php
/* PHP code */
?>
Anything within the opening and closing php
tags is assumed to be PHP code and should be executed by the PHP interpreter
Statements must end in a semicolon
Variables must start with a $ symbol
Line comments are denoted by //
Block comments are denoted by /* ... */
keywords, classes, functions and user-defined functions are NOT case sensitive
variable names ARE case sensitive
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php
$message = "Hello world";
echo "<p>$message</p>";
?>
</body>
</html>
Must start with a dollar sign ($) followed by a letter or the underscore character (_
)
Can only contain a-z,A-Z,0-9,
and _
Variable names are case sensitive
PHP data types:
String
Number: (Integer and Float)
Boolean
Array
Object
NULL
PHP is dynamically typed – types of variables do not need to be declared
PHP is generally weakly typed – some type conversions are automatic
The string type represents a sequence of characters
Categories of string
literal: delimited by single quotes (’...’
)
interpolated: delimited by double quotes ("..."
)
The escape character is the backslash (\)
The dot (.) operator performs string concatenation
A string can be defined over multiple lines
<?php
$name = "first_name
last name";
?>
Heredoc syntax preserves white space
<?php
$name = <<<_END
first_name
last name
_END;
?>
The <<<TOKEN
starts a heredoc
The token name is user defined, it typically should be a value not expected to be seen in the string
The ending token must be the first thing on the line followed by a semicolon (TOKEN;
)
There is no need to escape any characters in a heredoc
Operator | Description | Example |
---|---|---|
+ |
Addition | $a + 3 |
- |
Subtraction | $a - 3 |
* |
Multiplication | $a * 3 |
/ |
Division | $a / 3 |
% |
Modulus | $a % 3 |
++ |
Increment | ++$a |
– |
Decrement | –$a |
Operator | Example | Equivalent to |
---|---|---|
= |
$a = 3 |
$a = 3 |
+= |
$a += 3 |
$a = $a + 3 |
-= |
$a -= 3 |
$a = $a - 3 |
*= |
$a *= 3 |
$a = $a * 3 |
/= |
$a /= 3 |
$a = $a / 3 |
%= |
$a %= 3 |
$a = $a % 3 |
.= |
$a .= $b |
$a = $a . $b |
The type of a variable is implicitly converted based on the context in which the variable is used
In PHP this is called “Type Juggling”
<?php
$x = "10"; // string
$y = 3.14; // float
$z = $x * $y; // float
?>
The gettype
function returns a string representation of a variable’s type
(int), (integer)
cast to integer
(bool), (boolean)
cast to boolean
(float), (double), (real)
cast to float
(string)
cast to string
(array)
cast to array
(object)
cast to object
(unset)
cast to NULL
Constants are similar to variables, but the value cannot be changed once set
Syntax
<?php
define("NAME", "VALUE");
?>
NAME
is the name of the constant and is traditionally upper case
VALUE
is the value assigned to the constant
The syntax of a PHP file can be checked on the command line:
php -l FILE.php
The -l
(lower case L) is short for lint
If a syntax error exists, then the error and line number are reported
The basis of control flow is the boolean type
Relational operators return boolean values
Types of relational operators
Equality
Comparison
Logical
A boolean expresses a truth value (true or false)
The constants TRUE and FALSE are boolean literals
FALSE is set to the NULL type
Type values that are false when converted to booleans:
the boolean FALSE
the integer 0
the float 0.0
the empty string "" and the string "0"
an array with zero elements
the NULL type
Operator | Description | Example |
---|---|---|
== |
equal to | $a == 3 |
=== |
identical to | $a === 3 |
!= |
not equal to | $a != 3 |
!== |
not identical to | $a !== 3 |
> |
greater than | $a > 3 |
< |
less than | $a < 3 |
>= |
greater than or equal to | $a >= 3 |
<= |
less than or equal to | $a <= 3 |
Operator | Description | Example |
---|---|---|
&& |
and | $a == 3 && $b == 0 |
and |
low-precedence and | $a == 3 and $b == 0 |
|| |
or | $a == 3 || $b == 0 |
or |
low-precedence or | $a == 3 or $b == 0 |
! |
not | !($a == $b) |
xor |
exclusive or | $a xor $b |
The equality operator (==
) does implicit type coercion before the comparison
The identity operator (===
) prevents implicit type coercion, that is, for two operands to be identical, they must have the same type and value
Example:
<?php
$a = "1000" == "+1000"; // TRUE
$b = "1000" === "+1000"; // FALSE
$a = "1000" != "+1000"; // FALSE
$b = "1000" !== "+1000"; // TRUE
?>
if, else,
and elseif
<?php
if ($page == "Home") {/* code */}
elseif ($page == "About") {/* code */}
else {/* code */}
?>
switch
<?php
switch ($page) {
case ("Home"): {/* code */; break;}
case ("About"): {/* code */; break;}
default: {/* code */; break;}
}
?>
while
loops
do while
loops
for
loops
<?php
for ($count = 1; $count <= 10; ++$count) {
echo "The count is" . $count . "\n";
}
?>
In PHP an array is an ordered map that associates keys with values
PHP has two types of arrays
Numerically indexed arrays use integers as keys
Associative arrays typically use strings as keys
push consecutive values to the array
<?php
$a[] = "one";
$a[] = "two";
$a[] = "three";
?>
using explicit indices
<?php
$a[0] = "one";
$a[1] = "two";
$a[2] = "three";
?>
Associative arrays map keys other than integers to values
<?php
$b['one'] = 1;
$b['two'] = 2;
$b['three'] = 3;
?>
If multiple elements are declared with the same key, then only the value of the last element is used
A string containing an integer will be cast to an integer
A float is cast to an integer
A bool is cast to an integer
The null value will be cast to an empty string
Arrays and objects cannot be used as keys
The print_r
function prints a human readable representation of an array
An element of an array can be used as a variable for string interpolation purposes
echo "<p>$a[0]</p>";
If the key is not an integer then the array element must be surrounded by curly braces for string interpolation
echo "<p>${b['one']}</p>";
array
keywordArrays can be assigned with the array
keyword
<?php
$a = array("one", "two", "three");
$b = array('one' => 1,
'two' => 2,
'three' => 3);
?>
foreach
loopThe foreach loop can be used to iterate through the values of an array
Arrays with integer keys:
foreach($a as $element) {
echo "<p>$element</p>";
}
Associative arrays:
foreach($b as $key => $value) {
echo "<p>$key: $value</p>";
}
The value of a key can be an array
$tic_tac_toe = array(
array('X', ' ', 'O'),
array('O', 'O', 'X'),
array('X', 'O', ' ')
);
is_array
checks if a variable is an array type
count
returns the number of elements in an array
sort
performs an in-place sort of an array
explode
converts a string into an array
Superglobals are predefined variables that are provided by the PHP environment
$_GET:
variables passed to the current script via the HTTP GET method
$_POST:
variables passed to the current script via the HTTP POST method
$_COOKIE:
variables passed to the current script via HTTP cookies
$_SESSION:
session variables available to the current script
function function_name([parameter [, ...]])
{
// Statements
}
A definition starts with the word function
Next is the name of the function, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores
The parentheses are required
Zero or more parameters, separated by commas
return
keywordThe return
keyword is used to return a value from a function
<?php
$x = my_max(10, 5);
echo "<p>$x</p>";
function my_max($x, $y) {
return ($x > $y) ? $x : $y;
}
?>
Local variables are accessible in context in which they are defined
Global variables are accessible from all parts of the code
Static variables are accessible from the context in which they are defined, but retain their values
The value of a global variable can be assigned in a function by using the global
statement
<?php
$a = 10;
echo "<p>$a</p>";
f();
echo "<p>$a</p>";
function my_max() {
global $a;
$a = 5;
}
?>
<?php
counter();
counter();
function counter() {
static $count;
echo "<p>$count</p>";
$count += 1;
}
?>
The include
statement includes and evalutes the specified file
The include_once
statement includes and evalutes the specified file only once
The require
statement is identical to the include
statement, but if a failure occurs, the script is halted
The require_once
statement is identical to the include_once
statement, but if a failure occurs, the script is halted