Unit 2
Unit 2
Unit 2
With PHP you are not limited to output HTML. You can output images, PDF
files, and even Flash movies. You can also output any text, such as XHTML
and XML.
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses
a built-in PHP function "echo" to output the text "Hello World!" on a web
page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
In the example below, all three echo statements below are equal and legal:
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Look at the example below; only the first statement will display the value of
the $color variable! This is because $color, $COLOR, and $coLOR are treated
as three different variables:
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at the
code.
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
</body>
</html>
Example
Syntax for multiple-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Example
Using comments to leave out parts of the code:
<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the
value.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "ShillongCollege.com";
echo "I love $txt!";
?>
In PHP 7, type declarations were added. This gives an option to specify the
data type expected when declaring a function, and by enabling the strict
requirement, it will throw a "Fatal Error" on a type mismatch.
You will learn more about strict and non-strict requirements, and data type
declarations in the PHP Functions chapter.
PHP Functions
The real power of PHP comes from its functions.
PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.
Please check out our PHP reference for a complete overview of the PHP built-
in functions.
Syntax
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function
names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
Example
<?php
function writeMsg() {
echo "Hello world!";
}
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and
the name is used inside the function, which outputs several different first
names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and
$year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
In the following example we try to send both a number and a string to the
function without using strict:
Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it
will return 10
?>
To specify strict we need to set declare(strict_types=1);. This must be on the
very first line of the PHP file.
In the following example we try to send both a number and a string to the
function, but here we have added the strict declaration:
Example
<?php declare(strict_types=1); // strict requirement
Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
To declare a type for the function return, add a colon ( : ) and the type right
before the opening curly ( { )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
You can specify a different return type, than the argument types, but make
sure the return is the correct type:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Example
Use a pass-by-reference argument to update a variable:
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
PHP Constants
Constants are like variables except that once they are defined they cannot
be changed or undefined.
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
Syntax
define(name, value, case-insensitive)
Parameters:
Example
Create a constant with a case-sensitive name:
<?php
define("GREETING", "Welcome to ShillongCollege.com!");
echo GREETING;
?>
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is
true;
} else {
code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have
a good day!" if the current time is less than 20. Otherwise it will output
"Have a good night!":
<?php
$t = date("H");
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.
Syntax
while (condition is true) {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while
loop will write some output, and then increment the variable $x with 1. Then
the condition is checked (is $x less than, or equal to 5?), and the loop will
continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
The following example will output both the keys and the values of the given
array ($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
array();
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to
manage for most people.
Name Stock So
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two
indices (row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold:
".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold:
".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold:
".$cars[3][2].".<br>";
?>
PHP Strings
A string is a sequence of characters, like "Hello world!".
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
?>
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and optional
modifiers.
$exp = "/shillong/i";
Operator Description
^ It denotes the start of string.
$ It denotes the end of string.
. It denotes almost any single character.
() It denotes a group of expressions.
[] It finds a range of characters for example [xyz] means x, y or z .
[^] It finds the items which are not in range for example [^abc] means NOT a, b or c.
It finds for character range within the given item range for example [a-z] means a
– (dash)
through z.
| (pipe) It is the logical OR for example x | y means x OR y.
? It denotes zero or one of preceding character or item range.
* It denotes zero or more of preceding character or item range.
+ It denotes one or more of preceding character or item range.
{n} It denotes exactly n times of preceding character or item range for example n{2}.
{n, } It denotes atleast n times of preceding character or item range for example n{2, }.
{n, m} It denotes atleast n but not more than m times for example n{2, 4} means 2 to 4 of n.
\ It denotes the escape character.
Special Character Classes in Regular Expressions: Let us look into some of the special
characters used in regular expressions.
Special Character Meaning
\n It denotes a new line.
\r It denotes a carriage return.
\t It denotes a tab.
\v It denotes a vertical tab.
\f It denotes a form feed.
\xxx It denotes octal character xxx.
\xhh It denotes hex character hh.
Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined
functions for regular expressions in PHP. PHP provides the programmers to many useful
functions to work with regular expressions.
The below listed in-built functions are case-sensitive.
Function Definition
This function searches for a specific pattern against some string. It returns true if
preg_match()
pattern exists and false otherwise.
preg_match_a This function searches for all the occurrences of string pattern against the string.
ll() This function is very useful for search and replace.
This function searches for specific string pattern and replace the original string with
ereg_replace()
the replacement string, if found.
eregi_replace( The function behaves like ereg_replace() provided the search for pattern is not case
) sensitive.
This function behaves like ereg_replace() function provided the regular expressions
preg_replace()
can be used in the pattern and replacement strings.
The function behaves like the PHP split() function. It splits the string by regular
preg_split()
expressions as its parameters.
This function searches all elements which matches the regular expression pattern
preg_grep()
and returns the output array.
This function takes string and quotes in front of every character which matches the
preg_quote()
regular expression.
This function searches for a string which is specified by a pattern and returns true if
ereg()
found, otherwise returns false.
eregi() This function behaves like ereg() function provided the search is not case sensitive.
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
Example
Use a regular expression to do a case-insensitive search for "ShillongCollege" in a string:
<?php
$str = "Visit schools123";
$pattern = "/schools/";
$result=preg_match($pattern, $str); // Outputs 1
echo $result;
?>
Using preg_match_all()
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string
with another string.
Example
Use a case-insensitive regular expression to replace Microsoft with ShillongCollege in a
string:
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "School", $str); // Outputs "Visit Schools!"
?>
Example
<?php
if(preg_match($regex, $nameString)) {
else {
?>
Output:
Name string matching with regular expression
POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic
expressions which are called POSIX regular expressions. Some times, complex expression
are created by combining various elements or operators in regular expressions. The very basic
regex is the one which matches a single character.
Lets look into some of the POSIX regular expressions.
Regex Meaning
[0-9] It matches digit from 0 through 9.
[a-z] It matches any lowercase letter from a through z.
[A-Z] It matches any uppercase letter from A through Z.
[a-Z] It matches any lowercase letter a through uppercase letter Z.
Quantifiers in Regular Expression: Quantifiers are special characters which tell the
quantity, frequency or the number of instances or occurrence of bracketed character or group
of characters. They are also called as greedy and lazy expressions. Let us look into some of
the concepts and examples of quantifiers.
Quantifier Meaning
a+ It matches the string containing at least one a.
a* It matches the string containing zero or more a’s.
a? It matches any string containing zero or one a’s.
a{x} It matches letter ‘a’ exaclty x times .
a{2, 3} It matches any string containing the occurrence of two or three a’s.
a{2, } It matches any string containing the occurrence of at least two a’s.
a{2} It matches any string containing the occurrence of exactly two a’s.
a{, y} It matches any string containing the occurrence of not more than y number of a’s.
a$ It matches any string with ‘a’ at the end of it.
^a It matches any string with ‘a’ at the beginning of it.
[^a-zA-Z] It matches any string pattern not having characters from a to z and A to Z.
a.a It matches any string pattern containing a, then any character and then another a.
^.{3}$ It matches any string having exactly three characters.
or
(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-
z]{2,6}$/ix", $str))
• Create a regular expression pattern that matches any valid email address.
"^[a-zA-Z._]+@[a-zA-Z]+(\\.[a-zA-Z]+)+$"
• Any car registration number in the form ML01 A 1023 or ML04 1234. [ML0# (A-Z)
####] – The pattern should match string that start with ML0 followed by any digit
from 1-9, a space, any alphabet A-Z and a space (which is optional) and four digit
numbers.
"^ML[1-9]{2} +([A-Z] )?[0-9]{4}$"
"^[A-Z]{2}[1-9]{2} ([A-Z] )?[0-9]{4}$"
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number
in exponential form.
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
Classes and objects are the two main aspects of object-oriented
programming.
When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
Let's assume we have a class named Car. A Car can have properties like
model, color, etc. We can define variables like $model, $color, and so on, to
hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they
inherit all the properties and behaviors from the class, but each object will
have different values for the properties.
A variable of data type NULL is a variable that has no value assigned to it.
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>