String Length – strlen(“string”);
Word Count – str_word_count("Hello world!");
Search for text within a String – strops(“Hello world!”, “world”);
Upper Case – strtoupper(“text”);
Lower Case – strtolower();
Replace String – str_replace(“World”, “Dolly”, “Hello World!”);
Reverse – strrev()
Remove Whitespace – trim(“”)
Convert String to Array
$x = "Hello World!";
$y = explode(" ", $x);
//Use the print_r() function to display the result:
print_r($y);
/*
Result:
Array ( [0] => Hello [1] => World! )
Slicing
$x = "Hello World!";
echo substr($x, 6, 5);
Slice to the End
$x = "Hello World!";
echo substr($x, 6);
Slice From the End
Get the 3 characters, starting from the "o" in world (index -5):
$x = "Hello World!";
echo substr($x, -5, 3);
Negative Length
From the string "Hi, how are you?", get the characters starting from index 5,
and continue until you reach the 3. character from the end (index -3).
Should end up with "ow are y":
$x = "Hi, how are you?";
echo substr($x, 5, -3);
Function Description
addcslashes() Returns a string with backslashes in front of the spec
addslashes() Returns a string with backslashes in front of predefin
bin2hex() Converts a string of ASCII characters to hexadecimal
chop() Removes whitespace or other characters from the rig
chr() Returns a character from a specified ASCII value
chunk_split() Splits a string into a series of smaller parts
convert_cyr_string() Converts a string from one Cyrillic character-set to an
convert_uudecode() Decodes a uuencoded string
convert_uuencode() Encodes a string using the uuencode algorithm
count_chars() Returns information about characters used in a string
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string hashing
echo() Outputs one or more strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified output stream
get_html_translation_table() Returns the translation table used by htmlspecialcha
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and new lines (\n
hex2bin() Converts a string of hexadecimal values to ASCII cha
html_entity_decode() Converts HTML entities to characters
htmlentities() Converts characters to HTML entities
htmlspecialchars_decode() Converts some predefined HTML entities to characte
htmlspecialchars() Converts some predefined characters to HTML entitie
implode() Returns a string from the elements of an array
join() Alias of implode()
lcfirst() Converts the first character of a string to lowercase
levenshtein() Returns the Levenshtein distance between two string
localeconv() Returns locale numeric and monetary formatting info
ltrim() Removes whitespace or other characters from the lef
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file
metaphone() Calculates the metaphone key of a string
money_format() Returns a string formatted as a currency string
nl_langinfo() Returns specific local information
nl2br() Inserts HTML line breaks in front of each newline in a
number_format() Formats a number with grouped thousands
ord() Returns the ASCII value of the first character of a stri
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
quoted_printable_encode() Converts an 8-bit string to a quoted printable string
quotemeta() Quotes meta characters
rtrim() Removes whitespace or other characters from the rig
setlocale() Sets locale information
sha1() Calculates the SHA-1 hash of a string
sha1_file() Calculates the SHA-1 hash of a file
similar_text() Calculates the similarity between two strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitiv
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_rot13() Performs the ROT13 encoding on a string
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
strchr() Finds the first occurrence of a string inside another s
strcmp() Compares two strings (case-sensitive)
strcoll() Compares two strings (locale based string compariso
strcspn() Returns the number of characters found in a string b
characters are found
strip_tags() Strips HTML and PHP tags from a string
stripcslashes() Unquotes a string quoted with addcslashes()
stripslashes() Unquotes a string quoted with addslashes()
stripos() Returns the position of the first occurrence of a string
insensitive)
stristr() Finds the first occurrence of a string inside another s
strlen() Returns the length of a string
strnatcasecmp() Compares two strings using a "natural order" algorith
strnatcmp() Compares two strings using a "natural order" algorith
strncasecmp() String comparison of the first n characters (case-inse
strncmp() String comparison of the first n characters (case-sens
strpbrk() Searches a string for any of a set of characters
strpos() Returns the position of the first occurrence of a string
sensitive)
strrchr() Finds the last occurrence of a string inside another st
strrev() Reverses a string
strripos() Finds the position of the last occurrence of a string in
insensitive)
strrpos() Finds the position of the last occurrence of a string in
strspn() Returns the number of characters found in a string th
specified charlist
strstr() Finds the first occurrence of a string inside another s
strtok() Splits a string into smaller strings
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
strtr() Translates certain characters in a string
substr() Returns a part of a string
substr_compare() Compares two strings from a specified start position
sensitive)
substr_count() Counts the number of times a substring occurs in a s
substr_replace() Replaces a part of a string with another string
trim() Removes whitespace or other characters from both s
ucfirst() Converts the first character of a string to uppercase
ucwords() Converts the first character of each word in a string t
vfprintf() Writes a formatted string to a specified output stream
vprintf() Outputs a formatted string
vsprintf() Writes a formatted string to a variable
wordwrap() Wraps a string to a given number of characters
………………………………………………………………………..
PHP Numbers
Integer - is_int(), is_integer(), is_long()
Float – is_float(), id_double()
Number Strings : is_numeric()
is_nan() = check it is not a number
……………………………………………………………………………………
Data Types Conversion:
(string)
(int)
(float)
(bool): If a value is 0, NULL, false, or empty, the (bool) converts it into false, -
1 = true
(array) : When converting into arrays, most data types converts into an
indexed array with one element.
NULL values converts to an empty array object.
Objects converts into associative arrays where the property names becomes
the keys and the property values becomes the values:
(object)
(unset) - converts to data type NULL
…………………………………………………………………………………………………………………………………………….
MATH
pi() function returns the value of PI:
min(), max()
abs(-6.7)
sqrt(64) -
round(0.60) – nearest integer
rand(10,100),
pow(25,1/2)
………………………………………………………………………………………………………………………………………………….
const are always case-sensitive
define() has has a case-insensitive option.
const cannot be created inside another block scope, like inside a
function or inside an if statement.
define can be created inside another block scope.
define(name, value, case-insensitive);
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
Magic Constants
Constant Description
__CLASS__ If used inside a class, the class name is returned.
__DIR__ The directory of the file.
__FILE__ The file name including the full path.
__FUNCTION__ If inside a function, the function name is returned.
__LINE__ The current line number.
__METHOD__ If used inside a function that belongs to a class, both class and funct
__NAMESPACE__ If used inside a namespace, the name of the namespace is returned
__TRAIT__ If used inside a trait, the trait name is returned.
ClassName::class Returns the name of the specified class and the name of the namesp
PHP Operators
Arithmetic operators –
Modulus : % - Remainder of $x divided by $y
Exponentiation - ** Result of raising $x to the $y'th power
Assignment operators
Comparison operators
!== Not $x !== Returns true if $x is not equal to $y, or they are not of the
identical $y
<= Spaceship $x <=> Returns an integer less than, equal to, or greater than zer
> $y equal to, or greater than $y. Introduced in PHP 7.
Increment/Decrement operators
Logical operators
xor Xor $x xor $y True if either $x or $y is true, but not both
And (&&), or (||), !
String operators
. Concatenation $txt1 . $txt2 Concatenation of $tx
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $tx
Array operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x an
key/value pairs
=== Identity $x === $y Returns true if $x an
key/value pairs in th
same types
!= Inequality $x != $y Returns true if $x is
<> Inequality $x <> $y Returns true if $x is
!== Non-identity $x !== $y Returns true if $x is
Conditional assignment operators
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 =
The value of $x is expr3 if expr1 =
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 ex
If expr1 does not exist, or is NULL, t
Introduced in PHP 7
FOR EACH LOOP
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
Key Value
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y) {
echo "$x : $y <br>";
foreach Loop for Object of Class
Print the property names and values
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
$myCar = new Car("red", "Volvo");
foreach ($myCar as $x => $y) {
echo "$x: $y <br>";
#Result
color: red
model: Volvo
Foreach Byref
By default, changing an array item will not affect the original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") $x = "pink";
var_dump($colors);
By assigning the array items by reference (&$x), changes will affect the
original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as &$x) {
if ($x == "blue") $x = "pink";
var_dump($colors);
Alternative Syntax of ForEach
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) :
echo "$x <br>";
endforeach;
Functions :
Variable Number of Arguments
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
return $n;
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
The variadic argument must be the last argument:
Strict Type
<?php declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
return $a + $b;
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an
error will be thrown
?>
PHP Array Types
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
$myArr = array("Volvo", 15, ["apples", "bananas"],
myFunction);
array_push($cars, "Ford");
Associative Arrays
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
echo $car["model"];
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
Another Method
$myCar = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
Excecute a Function Item
function myFunction() {
echo "I come from a function!";
$myArr = array("Volvo", 15, myFunction);
//$myArr = array("car" => "Volvo", "age" => 15, "message" =>
myFunction);
$myArr[2]();
Types of Array :
Indexed Array :
Associative Arrays :
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
Create Arrays : $cars = ["Volvo", "BMW",
"Toyota"];
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars["bmw"] = "cherries";
Access Array Items: $cars["model"]; $cars[0];
Add Array Items: $cars = array("brand" =>
"Ford", "model" => "Mustang");
$cars["color"] = "Red";
$fruits = array("Apple", "Banana", "Cherry"); // Indexed
array_push($fruits, "Orange", "Kiwi", "Lemon");
$cars = array("brand" => "Ford", "model" => "Mustang"); //
Associative
$cars += ["color" => "red", "year" => 1964];
Remove Array Items:
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1); // last one is no. of items to delete
unset() – to delete existing array items.
unset($cars[1]);
unset($cars[0], $cars[1]);
unset($cars["model"]); // Associative Array
array_diff() – to remove items from an associative array.
$cars = array("brand" => "Ford", "model" => "Mustang", "year" =>
1964);
$newarray = array_diff($cars, ["Mustang", 1964]);
array_pop() function removes the last item of an
array.
$cars = array("Volvo", "BMW", "Toyota");
array_pop($cars);
array_shift() function removes the first item of an
array.
array_shift($cars);
Sorting Arrays:
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the
value
ksort() - sort associative arrays in ascending order, according to the
key
arsort() - sort associative arrays in descending order, according to the
value
krsort() - sort associative arrays in descending order, according to the
key
Multidimensional Arrays:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
echo "</ul>";
PHP Array Functions
PHP has a set of built-in functions that you can use on arrays.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or
uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the
input array
array_combine() Creates an array by using the elements from
one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences
(compare values only)
array_diff_assoc() Compare arrays, and returns the differences
(compare keys and values)
array_diff_key() Compare arrays, and returns the differences
(compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences
(compare keys and values, using a user-defined
key comparison function)
array_diff_ukey() Compare arrays, and returns the differences
(compare keys only, using a user-defined key
comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback
function
array_flip() Flips/Exchanges all keys with their associated
values in an array
array_intersect() Compare arrays, and returns the matches
(compare values only)
array_intersect_assoc() Compare arrays and returns the matches
(compare keys and values)
array_intersect_key() Compare arrays, and returns the matches
(compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches
(compare keys and values, using a user-defined
key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches
(compare keys only, using a user-defined key
comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made
function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array
recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a
specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an
array
array_rand() Returns one or more random keys from an
array
array_reduce() Returns an array as a string, using a user-
defined function
array_replace() Replaces the values of the first array with the
values from following arrays
array_replace_recursive() Replaces the values of the first array with the
values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns
the key
array_shift() Removes the first element from an array, and
returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an
array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences
(compare values only, using a user-defined key
comparison function)
array_udiff_assoc() Compare arrays, and returns the differences
(compare keys and values, using a built-in
function to compare the keys and a user-
defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences
(compare keys and values, using two user-
defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches
(compare values only, using a user-defined key
comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches
(compare keys and values, using a built-in
function to compare the keys and a user-
defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches
(compare keys and values, using two user-
defined key comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of
an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an
array
array_walk_recursive() Applies a user function recursively to every
member of an array
arsort() Sorts an associative array in descending order,
according to the value
asort() Sorts an associative array in ascending order,
according to the value
compact() Create array containing variables and their
values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Deprecated from PHP 7.2. Returns the current
key and value pair from an array
end() Sets the internal pointer of an array to its last
element
extract() Imports variables into the current symbol table
from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order,
according to the key
ksort() Sorts an associative array in ascending order,
according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural
order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of
elements
reset() Sets the internal pointer of an array to its first
element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined
comparison function and maintains the index
association
uksort() Sorts an array by keys using a user-defined
comparison function
usort() Sorts an array by values using a user-defined
comparison function
PHP Global Variables - Superglobals
The PHP superglobal variables are:
$GLOBALS- is an array that contains all global variables.
$GLOBALS["x"] = 100; global $x;
$_SERVER
echo $_SERVER['PHP_SELF'];
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing s
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Int
server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as ww
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as A
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information
HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the p
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the reques
1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current requ
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the cur
as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current reques
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (n
not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP proto
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is vie
page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is vi
page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machi
with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN d
server configuration file (if your script runs on a
the value defined for that virtual host) (such as
[email protected])
$_SERVER['SERVER_PORT'] Returns the port on the server machine being us
server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name
server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the curren
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
?>
$_REQUEST
$_POST$_POST['fname'];
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "demo_phpfile.php");
xhttp.setRequestHeader("Content-type", "application/x-
www-form-urlencoded");
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.send("fname=Mary");
}
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
$_GET
$_GET['web']
$_FILES
$_ENV
$_COOKIE
$_SESSION
PHP Regular Expressions
PHP Regular Expression Functions
Function Description
preg_filter() Returns a string or an array with pattern matches replac
matches were found
preg_grep() Returns an array consisting only of elements from the in
matched the pattern
preg_last_error() Returns an error code indicating the reason that the mos
expression call failed
preg_match() Finds the first match of a pattern in a string
preg_match_all() Finds all matches of a pattern in a string
preg_replace() Returns a string where matches of a pattern (or an array
replaced with a substring (or an array of substrings) in a
preg_replace_callback() Given an expression and a callback, returns a string whe
expression are replaced with the substring returned by t
preg_replace_callback_array() Given an array associating expressions with callbacks, re
all matches of each expression are replaced with the sub
the callback
preg_split() Breaks a string into an array using matches of a regular
separators
preg_quote() Escapes characters that have a special meaning in regul
putting a backslash in front of them
Regular Expression Modifiers
Modifiers can change how a search is performed.
Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for the beginnin
will match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns
Regular Expression Patterns
Brackets are used to find a range of characters:
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at t
this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number
Quantifiers
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's
Note: If your expression needs to search for one of the special characters
you can use a backslash ( \ ) to escape them. For example, to search for one
or more question marks you can use the following expression: $pattern = '/\?
+/';
Grouping
You can use parentheses ( ) to apply quantifiers to entire patterns. They
also can be used to select parts of the pattern to be used as a match.
Example
Use grouping to search for the word "banana" by looking for ba followed by
two instances of na:
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str);
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);