Web Development BCS IV Sem Unit II
Web Development BCS IV Sem Unit II
With PHP you are not limited to output HTML. You can output images or PDF files. You can
also output any text, such as XHTML and XML.
Why PHP?
PHP 7 is much faster than the previous popular stable release (PHP 5.6)
PHP 7 has improved Error Handling
PHP 7 supports stricter Type Declarations for function arguments
PHP 7 supports new operators (like the spaceship operator: <=>)
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
?>
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
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
In the example below, all three echo statements below are equal and legal:
Example
ECHO is the same as echo:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</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
$COLOR is not same as $color:
<html>
<body>
<?php
$color = "red";
?>
</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.
Example
Syntax for comments in PHP code:
/* This is a
multi-line comment */
Any text between // and the end of the line will be ignored (will not be executed).
You can also use # for single line comments, but in this tutorial we will use //.
Example
A comment before the code:
Example
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
Multi-line comment as an explanation:
/*
*/
PHP Variables
Variables are "containers" for storing information.
Example
<html>
<body>
<?php
$x = 5;
$y = "John";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
o/p
5
John
In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
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
<html>
<body>
<?php
$txt = "W3Schools.com";
?>
</body>
</html>
o/p
I love W3Schools.com!
The following example will produce the same output as the example above:
Example
<html>
<body>
<?php
$txt = "W3Schools.com";
?>
</body>
</html>
Example
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the
variable.
Example
<html>
<body>
$x = 5; // $x is an integer
$y = "John"; // $y is a string
<?php
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
?>
</body>
</html>
o/p
5John
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
Example
The var_dump() function returns the data type and the value:
<html>
<body>
<?php
$x = 5;
var_dump($x);
?>
</body>
</html>
Output-
int(5)
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.
PHP Reference
The PHP reference contains different categories of all PHP functions, keywords and constants,
along with examples.
Array, Calendar, Date, Directory, Error, Exception, Filesystem, Filter, FTP, JSON,
Keywords, Libxml, Mail, Math, Misc, MySQLi, Network, Output, RegEx, Simple
XML, Stream, String, Var, Handling, XML, Parser, Zip, Timezones.
Create a Function
A user-defined function declaration starts with the keyword function, followed by the name of the
function:
Example
function myMessage() {
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!
Call a Function
To call the function, just write its name followed by parentheses ():
Example
<html>
<body>
<?php
function myMessage() {
myMessage();
?>
</body>
</html>
o/p
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:
<html>
<body>
<?php
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
o/p
Example
<html>
<body>
<?php
$z = $x + $y;
return $z;
}
?>
</body>
</html>
o/p
5 + 10 = 15
7 + 13 = 20
2+4=6
When a function argument is passed by reference, changes to the argument also change the
variable that was passed in. To turn a function argument into a reference, the & operator is used:
Example
<html>
<body>
<?php
function add_five(&$value) {
$value += 5;
$num = 2;
add_five($num);
echo $num;
?>
</body>
</html>
o/p
PHP Array
An array is a special variable that can hold many values under a single name, and you can access
the values by referring to an index number or name.
Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
<!DOCTYPE html>
<html>
<body>
<?php
echo count($cars)."<br>";
echo $cars[0];
?>
</body>
</html>
Output:
3
Volvo
By default, the first item has index 0, the second item has item 1, etc.
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
var_dump($cars);
?>
</pre>
</body>
</html>
Output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
echo $cars[0];
Change Value
To change the value of an array item, use the index number:
Example
$cars[1] = "Ford";
var_dump($cars);
Index Number
The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but
there are exceptions.
New items get the next index number, meaning one higher than the highest existing index.
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
And if you use the array_push() function to add a new item, the new item will get the index 3:
Example
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
array_push($cars, "Ford");
var_dump($cars);
?>
</pre>
</body>
</html>
Output:
array(4) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
[3]=>
string(4) "Ford"
}
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
var_dump($car);
?>
</pre>
</body>
</html>
Output:
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
<!DOCTYPE html>
<html>
<body>
<?php
echo $car["model"];
?>
</body>
</html>
Output:
Mustang
Change Value
To change the value of an array item, use the key name:
Example
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$car["year"] = 2024;
var_dump($car);
?>
</pre>
</body>
</html>
Output:
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1
for each item, so the array above could also be created with keys:
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
var_dump($cars);
?>
</pre>
</body>
</html>
Output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Declare
Empty Array
You can declare an empty array first, and add items to it later:
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
var_dump($cars);
?>
</pre>
</body>
</html>
Output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
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.
The dimension of an array indicates the number of indices you need to select an element.
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):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
?>
</body>
</html>
Output:
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_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_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_map() Sends each value of an array to a user-made function, which returns new
values
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_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_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)
each() Deprecated from PHP 7.2. Returns the current key and value pair from
an array
extract() Imports variables into the current symbol table from an array
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_name() and get_name() for setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties and functions are called methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has
all the properties and methods defined in the class, but they will have different property values.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Output:
Apple
Banan
where A is the base class (also called parent called) and B is called a subclass or child class.
Child class inherits public and protected methods of parent class. Child class may redefine or
override any of inherited methods. If not, inherited methods will retain their functionality as
defined in parent class, when used with object of child class.
Definition of parent class must precede child class definition. In this case, definition of A class
should appear before definition of class B in the script.
Example
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?>
If autoloading is enabled, definition of parent class is obtained by loading the class script.
Inheritance Example
Following code shows that child class inherits public and protected members of parent class
Example
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class
";
}
protected function protectedmethod(){
echo "This is protected method of parent class
";
}
private function privatemethod(){
echo "This is private method of parent class
";
}
}
class childclass extends parentclass{
public function childmethod(){
$this->protectedmethod();
//$this->privatemethod(); //this will produce error
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>
Output
Strings in PHP are surrounded by either double quotation marks, or single quotation marks.
<html>
<body>
<?php
echo "Hello";
print "Hello";
?>
</body>
</html>
Output
HelloHello
E.g. when there is a variable in the string, it returns the value of the variable:
Example
Double quoted string literals perform operations for special characters:
<html>
<body>
<?php
$x = "John";
</body>
</html>
Output
Hello John
Function Description
chop() Removes whitespace or other characters from the right end of a string
ltrim() Removes whitespace or other characters from the left side of a string
strchr() Finds the first occurrence of a string inside another string (alias of
strstr())
strcspn() Returns the number of characters found in a string before any part of
some specified characters are found
stristr() Finds the first occurrence of a string inside another string (case-
insensitive)
strpos() Returns the position of the first occurrence of a string inside another
string (case-sensitive)
strripos() Finds the position of the last occurrence of a string inside another
string (case-insensitive)
strrpos() Finds the position of the last occurrence of a string inside another
string (case-sensitive)
strspn() Returns the number of characters found in a string that contains only
characters from a specified charlist
strstr() Finds the first occurrence of a string inside another string (case-
sensitive)
substr_compare() Compares two strings from a specified start position (binary safe and
optionally case-sensitive)
Syntax
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
<html>
<body>
<?php
?>
</body>
</html>
Output:
Today is 2020/11/03
Today is 2020.11.03
Today is 2020-11-03
Today is Tuesday
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
<html>
<body>
<?php
echo "The time is " . date("h:i:sa");
?>
</body>
</html>
Output:
The time is 10:29:46am
Note: These functions depend on the locale settings of your server. Remember to take daylight
saving time and leap years into consideration when working with these functions.
date_sunrise() Returns the sunrise time for a specified day and location
date_sunset() Returns the sunset time for a specified day and location