PHP Examples
PHP Install
PHP Syntax
Write text to the output using PHP
Keywords, classes, functions, and user-defined functions ARE NOT case-sensitive
Variable names ARE case-sensitive
PHP Comments
Single-line comment before code line
Single-line comment at the end of code line
Use comment to prevent code from being executed
Multi-line comment
Multi-line comment to ignore code
PHP Variables
Create variables
Output some text and the value of a variable
Output the sum of two variables
Assign the same value to multiple variables in one line
Use var_dump() to return the data type of variables
Global scope (variable outside function)
Local scope (variable inside function)
Static scope (let a local variable not be deleted after execution of function)
Use the global keyword to access a global variable from within a function
Use the $GLOBALS[] array to access a global variable from within a function
PHP Echo and Print
Echo - Output text
Echo - Output variables
Echo - Single or double quotes?
Print - Output text
Print - Output variables
Print - Single or double quotes?
PHP Data Types
PHP Strings
strlen() - Return the length of a string
str_word_count() - Count the number of words in a string
str_contains() - Check if a string contains a specific substring
strpos() - Search for a specific text within a string
strtoupper() - Returns a string in upper case
strtolower() - Returns a string in lower case
str_replace() - Replaces some characters with some other characters in a string
strrev() - Reverse a string
trim() - Removes any whitespace from the beginning/end of a string
explode() - Splits a string into an array
substr() - Extract a part of a string (slice a string)
Use escape character
PHP Numbers
is_int() - Check if variable is of type integer
is_float() - Check if variable is of type float
is_infinite() - Check if a numeric value is infinite
is_nan() - Check if a value is "Not A Number" (NAN)
is_numeric() - Check if a variable is a number or a numeric string
is_numeric() - Check if a variable is a number or a numeric string
intval() - Return the integer value of a variable
PHP Casting
Cast to String
Cast to Integer
Cast to Float
Cast to Boolean
Cast to Array
Cast to Object
Cast to NULL
PHP Math
pi() - Return value of PI
min(), max() - Find the lowest and highest value in a list of arguments
abs() - Return the absolute (positive) value of a number
sqrt() - Return the square root of a number
round() - Round a floating-point number to its nearest integer
rand() - Generate a random number
rand() - Generate a random number between 10 and 100
PHP Constants
define() - Create a constant
Declare a constant inside a function, and output it outside the function
const keyword - Create a constant
Create Array constants with define() or const
PHP Magic Constants
The __CLASS__ constant
The __DIR__ constant
The __FILE__ constant
The __FUNCTION__ constant
The __FUNCTION__ constant
The __METHOD__ constant
The __NAMESPACE__ constant
The __TRAIT__ constant
The ClassName::class constant
PHP Operators
Arithmetic operator: Addition (+)
Arithmetic operator: Subtraction (-)
Arithmetic operator: Multiplication (*)
Arithmetic operator: Division (/)
Arithmetic operator: Modulus (%)
Arithmetic operator: Exponentiation (**)
Assignment operator: x = y
Assignment operator: x += y
Assignment operator: x -= y
Assignment operator: x *= y
Assignment operator: x /= y
Assignment operator: x %= y
Comparison operator: Equal (==)
Comparison operator: Identical (===)
Comparison operator: Not equal (!=)
Comparison operator: Not equal (<>)
Comparison operator: Not identical (!==)
Comparison operator: Greater than (>)
Comparison operator: Less than (<)
Comparison operator: Greater than or equal (>=)
Comparison operator: Less than or equal (<=)
Comparison operator: Spaceship (<=>)
Increment operator: ++$x
Increment operator: $x++
Decrement operator: --$x
Decrement operator: $x--
Logical operator: and
Logical operator: or
Logical operator: xor
Logical operator: && (and)
Logical operator: || (or)
Logical operator: not
String operator: Concatenation of $txt1 and $txt2
String operator: Appends $txt2 to $txt1
Array operator: Union (+)
Array operator: Equality (==)
Array operator: Identity (===)
Array operator: Inequality (!=)
Array operator: Inequality (<>)
Array operator: Non-identity (!==)
Conditional assignment operator: Ternary (?:)
Conditional assignment: Null coalescing (??)
PHP If Statements
The if statement executes some code only if the specified condition is true
The if...else statement executes some code if a condition is true, and another code if condition is false
The if...elseif...else statement executes different codes for more than two conditions
Shorthand if
Shorthand if...else
Nested if
PHP Switch Statement
The switch statement performs different actions based on different conditions
The default keyword specifies the code to run if there is no case match
Combining cases
PHP Match Expression
The match expression performs different actions based on different conditions
Match multiple values for the same code block
PHP Loops
while loop - Loops through a block of code as long as the specified condition is true
do...while loop - Loops through a block of code at least once, and then repeats the loop as long as the specified condition is true
Another do...while loop
for loop - Loops through a block of code a specified number of times
foreach loop - Loops through a block of code for each element in an array or each property in an object
PHP Functions
Create and call a function
Function with one parameter
Function with two parameters
Function with default parameter value
Function with return value
Passing arguments by reference
Variable number of parameters
PHP Arrays
Create and display an indexed array
Access a specific array item with index number
Change value of array item
Loop through an indexed array
Create and display an associative array
Access a specific array item with key name
Change value of array item
Loop through an associative array
Add more array items to the end of an indexed array
Add more array items to the end of an associative array
array_push() - Add one or more array items to the end of an array
array_unshift() - Add one or more array items to the beginning of an array
array_splice() - Remove a portion of an array and replace it with new items
array_merge() - Merge two or more arrays
array_pop() - Remove the last item of an array
array_shift() - Remove the first item of an array
sort() - Sorts an indexed array in ascending order
rsort() - Sorts an indexed array in descending order
asort() - Sorts an associative array in ascending order (value)
arsort() - Sorts an associative array in descending order (value)
ksort() - Sorts an associative array in ascending order (key)
krsort() - Sorts an associative array in descending order (key)
Create a multidimensional array
Loop through a multidimensional array (for loop)
Loop through a multidimensional array (foreach loop)
PHP Superglobals
$GLOBAL - Used to access global variables from anywhere in the script
$_SERVER - Holds information about headers, paths, and script locations
$_REQUEST - Contains data from submitted forms, URL query strings, and HTTP cookies
$_POST - Contains an array of variables received via the HTTP POST method
$_GET - Contains an array of variables received via the HTTP GET method
PHP Regular Expressions
Regex Modifier: i
Regex Modifier: m
Regex Modifier: [abc]
Regex Modifier: [^abc]
Regex Modifier: [a-z]
Regex Modifier: [A-z]
Regex Modifier: [A-Z]
Regex Modifier: [123]
Regex Modifier: [0-5]
Regex Modifier: [0-9]
Regex Modifier: |
Regex Modifier: .
Regex Modifier: ^
Regex Modifier: $
Regex Modifier: \d
Regex Modifier: \D
Regex Modifier: \s
Regex Modifier: \S
Regex Modifier: \w
Regex Modifier: \W
Regex Modifier: \b
Regex Modifier: \u
Regex Modifier: n+
Regex Modifier: n{3}
Regex Modifier: n{2, 5}
Regex Modifier: n{3,}
PHP Regular Expression Functions
preg_match() - Returns 1 if the pattern was found in the string, otherwise 0
preg_match_all() - Returns how many matches were found for a pattern in a string
preg_replace() - Replaces all matches of the pattern in a string with another string
preg_split() - Splits a string into an array using matches of a regular expression as separators
preg_grep() - Returns an array containing only elements from the input that match the given pattern
Regular Exp Functions explained
PHP Form Validation
PHP Date and Time
date() Format today's date in several ways
Automatically update the copyright year
Output the current time (server time)
Set timezone, then output current time
Return default timezone
mktime() - Create a date and time from a number of parameters
Format a timestamp to a readable date and time
strtotime() - Convert strings to dates
Output the dates for the next six Saturdays
PHP Include Files
Use include to include "footer.php" in a page
Use include to include "menu.php" in a page
Use include to include "vars.php" in a page
Use include to include a non-existing file
Use require to include a non-existing file
PHP File Handling
PHP File Open/Read/Close
Use fopen(), fread(), and fclose() to open, read, and close a file
Use fgets() to read a single line from a file
Use feof() to read through a file, line by line, until end-of-file is reached
Use fgetc() to read a single character from a file
File Open/Read/Close explained
PHP Sessions
Start a new session, and set session variables
Get session variable values
Get all session variable values
Modify a session variable
Destroy a session
PHP Filters
filter_list() - List all supported filter names and ids
Sanitize and validate an email
Sanitize and validate a URL
Validate an integer
Validate an integer that is 0
Validate an IP address
Validate an integer within a range
Validate IPv6 address
Validate URL - Must contain querystring
Sanitize string - Remove characters with ASCII value > 127
PHP Callback Functions
Use a named function as a callback
Use an anonymous function as a callback
Callbacks in user defined functions
PHP and JSON
Encode an associative array into a JSON object
Encode an indexed array into a JSON object
Decode JSON data into a PHP object
Decode JSON data into an associative array
Access the values from a PHP object
Access the values from an associative array
Loop through the values of a PHP object
Loop through the values of an associative array
PHP Exceptions
Throw an exception without catching it
Display a message when an exception is thrown, and continue script
Display a message when an exception is thrown, and then indicate that the process is complete
Output information about an exception that was thrown
PHP Object-Oriented Programming (OOP)
Create a class and two objects
The instanceof keyword checks if an object belongs to a specific class
__construct() - Create a constructor
__destruct() - Create a destructor
Access modifier: Public
Access modifier: Private
Access modifier: Protected
Inheritance
A constant can be accessed fom outside the class
A constant can be accessed fom inside the class
Abstract class
Abstract method with argument
Define and use an Interface
Use an Interface 2
Define and use a Trait
Use multiple Traits
Declare a Static method
Declare a Static property
PHP MySQL Database
Select data with MySQLi (Object-oriented)
Select data with MySQLi (Procedural)
Put result in an HTML table (MySQLi Object-oriented)
Select and filter data with MySQLi (Object-oriented)
Select and filter data with MySQLi (Procedural)
Select and order by with MySQLi (Object-oriented)
Select and order by with MySQLi (Procedural)
PHP SimpleXML Parser
simplexml_load_string() - Read XML data from a string
simplexml_load_file() - Read XML data from a file
Get node values
Get node values of specific elements
Get node values - loop
Get attribute values
Get attribute values - loop