UNIT-1 Introduction to PHP
Introduction to PHP
• PHP is a server scripting language and a powerful tool for making dynamic and interactive Web pages.
• PHP is a widely-used, free and efficient alternative to competitors such as Microsoft's ASP.
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
A Brief History of PHP
• PHP was originally created by Rasmus Lerdorf in 1994. Programmer Rasmus Lerdorf initially created a
set of C scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts
performed tasks such as displaying his resume and recording his web‐page traffic.
• These were released and extended to include a package called the Form Interpreter (PHP/FI). While PHP
originally stood for "Personal Home Page", now it is known as "PHP: Hypertext Preprocessor".
• In 1997 Zeev Suraski and Andi Gutmans along with Rasmus rewrite PHP and released PHP version 3.0 in
June 1998. After this release PHP becomes so much popular.
• The PHP version 4.0 was launched in May 2000.This version includes session handling, output buffering
and support for wide variety of web server platforms.
• The PHP 5.0 version released in 2004 with object oriented programming concept.
How PHP works?
• PHP sits between your browser and the web server. When you type in the URL of a PHP website in your
browser, your browser sends a request to the web server. The web server then calls the PHP script on that
page. The PHP module executes the script which then sends the result in the form of HTML back to your
browser which you seen on the screen
Relationship between Apache, MySQL and PHP (AMP Module)
AMP stands for Apache MySQL PHP
PHP
PREPARED BY : TWINCLE VYAS
• PHP is a server side scripting that was designed for creating dynamic websites.
• PHP script runs on a web server.
• PHP is loosely type language because it converts a data type of variable automatically.
• PHP programs run on web server.
Apache
• To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web Server
that, once installed on a computer, allows developers to test PHP scripts locally; this makes it an invaluable
piece of your local development environment.
• Like all web servers, Apache accepts an HTTP request and serves an HTTP response.
• The Apache Server provides full range of Web Server features, including CGI, SSL and virtual domains.
• Apache is open source free software distributed by the Apache Software Foundation.
MySQL
• Additionally, dynamic websites are dependent on stored information that can be modified quickly and
easily; this is the main difference between a dynamic site and a static HTML site.
• However, PHP doesn’t provide a simple, efficient way to store data. This is where a relational database
management system like MySQL comes into play.
• PHP provides native support for it and the database is free, open‐source project.
• MySQL is a relational database management system (DBMS). Essentially, this means that MySQL allows
users to store information in a table‐based structure, using rows and columns to organize different pieces of
data.
Open Source
• In general, open source refers to any program whose source code is made available for use or
modification. Open source software is usually developed as a public collaboration and made freely
available. It means can be used without purchasing any license.
• Open Source is a certification mark owned by the Open Source Initiative (OSI). Developers of software
that is intended to be freely shared and possibly improved and redistributed by others can use the Open
Source trademark if their distribution terms conform to the OSI's Open Source Definition. To summarize,
the Definition model of distribution terms require that: ✓
redistributed to anyone else without any restriction.
The source code must be made available (so that the receiving party will be able to improve or modify it).
• Example of Open Source: Linux, Apache, MySQL, PHP.
PAREPARED BY : TWINCLE VYAS
PAREPARED BY : TWINCLE VYAS
PAREPARED BY : TWINCLE VYAS
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
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).
• To create a constant, use the define() function.
• Syntax: define(name, value, case-insensitive)
✓ name: Specifies the name of the constant
✓ value: Specifies the value of the constant
✓ case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.
• The example below creates a constant with a case-insensitive name:
• Example:
<? php
define("GREETING", "Welcome to W3Schools.com!", true); // case-insensitive constant name
echo greeting;
?>
constant()
• The constant() function returns the value of a constant.
PAREPARED BY : TWINCLE VYAS
Syntax: constant(constant)
✓ Constant: Required. Specifies the name of the constant.
Example:
<?php
define("GREETING","Hello you! How are you today?");
echo constant("GREETING");
?>
PHP Magic constants (predefined constants)
• PHP provides a large number of predefined constants to any script which it runs.
• There are five magical constants that change depending on where they are used. For example, the value of
LINE depends on the line that it's used on in your script. These special constants are case-insensitive and are
as follows:
• A few "magical" PHP constants are given below:
Name Description
LINE The current line number of the file.
FILE__ The full path and filename of the file.
FUNCTION__ The function name. This constant returns the
function name as it was declared.
CLASS The class name. This constant returns the
class name as it was declared.
METHOD The class method name. The method name is
returned as it was declared.
PHP Variable and value types
Variables are "containers" for storing information.
Declaring Variables: $var_name=value;
✓ 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 character and underscore (A-z, 0-9, and _ )
✓ Variable names are case-sensitive ($age and $AGE are two different variables)
Rules for PHP variables:
Example:
$txt = "Hello world!”; // variable $txt will hold the value Hello world!
$x = 5; // variable $x will hold the value 5
$y = 10.5; // variable $y will hold the value 10.5
Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be referenced/used.
• PHP has three different variable scopes:
PAREPARED BY : TWINCLE VYAS
✓ local
✓ global
✓ static
Global
• A variable declared outside a function has a global scope and can only be accessed outside a function:
<?php
$x = 5; // global scope
function myTest()
{
echo "Variable x inside function is: $x"; // using x inside this function will generate an error
}
//myTest();
echo "Variable x outside function is: $x";
?>
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function): global $x;
Local
• A variable declared within a function has a local scope and can only be accessed within that function.
<?php
function myTest()
{
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
//echo "Variable x outside function is: $x"; // using x outside the function will generate an error
?>
Static
• Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we
want a local variable not to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
PAREPARED BY : TWINCLE VYAS
echo "<br>";
myTest();
?>
Output:
0
1
2
• Then, each time the function is called, that variable will still have the information it contained from the last
time the function was called.
PHP | Decision Making
PHP allows us to perform actions based on some type of conditions that may be logical or comparative.
Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as
asked by the user. It’s just like a two- way path. If you want something then go this way or else turn that
way. To use this feature, PHP provides us with four conditional statements:
if statement
if…else statement
if…elseif…else statement
switch statement
Let us now look at each one of these in details:
1. if Statement: This statement allows us to set a condition. On being TRUE, the following block
of code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
PAREPARED BY : TWINCLE VYAS
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the block of code within
if will be executed. But what if the condition is not TRUE and we want to perform an action? This is
where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets
executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
PAREPARED BY : TWINCLE VYAS
if…elseif…else Statement: This allows us to use multiple if…else statements. We use this when there are
multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
PAREPARED BY : TWINCLE VYAS
switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches
the condition and appropriately executes a particular case block. It first evaluates an expression and then
compares with the values of each case. If a case matches then the same case is executed. To use switch,
we need to get familiar with two different keywords namely, break and default.
1. The break statement is used to stop the automatic control flow into the next cases and exit
from the switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
PAREPARED BY : TWINCLE VYAS
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
default: code to be executed if n != any case;
PAREPARED BY : TWINCLE VYAS
PAREPARED BY : TWINCLE VYAS
Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of writing if…else, called
Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three operands: a
condition to check, a result for TRUE and a result for FALSE.
Syntax:
(condition) ? if TRUE execute this : otherwise execute this;
Loop In PHP
Like any other language, loop in PHP is used to execute a statement or a block of statements, multiple
times until and unless a specific condition is met. This helps the user to save both time and effort of
writing the same code multiple times.
PHP supports four types of looping techniques;
1. for loop
2. while loop
3. do-while loop
4. foreach loop
for loop: This type of loops is used when the user knows in advance, how many times the block needs to
execute. That is, the number of iterations is known beforehand. These type of loops are also known as
entry-controlled loops. There are three main parameters to the code, namely the initialization, the te st
condition and the counter.
Syntax:
for (initialization expression; test condition; update expression) {
// code to be executed
}
PAREPARED BY : TWINCLE VYAS
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value,
then check whether this variable is less than or greater than counter value. If statement is true, then loop
body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: $num = 1;
Test Expression: In this expression we have to test the condition. If the condition evaluates to true
then we will execute the body of loop and go to update expression otherwise we will exit from the
for loop. For example: $num <= 10;
Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: $num += 2;
Example:
while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at
the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on
executing it as long as the condition holds true.
Syntax:
PAREPARED BY : TWINCLE VYAS
while (if the condition is true) {
// code is executed
}
do-while loop: This is an exit control loop which means that it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at least once on using the
do…while loop. After executing once, the program is executed as long as the condition holds true.
Syntax:
do {
//code is executed
} while (if condition is true);
PAREPARED BY : TWINCLE VYAS
PAREPARED BY : TWINCLE VYAS
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:
PAREPARED BY : TWINCLE VYAS
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.
This example skips the value of 4:
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
PAREPARED BY : TWINCLE VYAS
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.
PHP Comparison Operators
PAREPARED BY : TWINCLE VYAS
The PHP comparison operators are used to compare two values (number or string):
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
PAREPARED BY : TWINCLE VYAS
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
PHP String Operators
PHP has two operators that are specially designed for strings.
PHP Array Operators
The PHP array operators are used to compare arrays.
PAREPARED BY : TWINCLE VYAS
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:
Arrays
• An array is a single variable that can hold more than one value at once.
• You can think of an array as a list of values.
• Each value within an array is called an element, and each element is referenced by its own index, which is
unique to that array.
• To access an elements value — whether you are creating, reading, writing, or deleting the element you use
that elements index.
Types of Array
• In PHP, there are three types of arrays:
PAREPARED BY : TWINCLE VYAS
✓ Indexed arrays (Numeric arrays) - Arrays with a numeric index
✓ Associative arrays - Arrays with named keys
✓ Multidimensional arrays (Nested arrays) - Arrays containing one or more arrays
Indexed arrays (Numeric arrays)
• In numeric array each element having numeric key associated with it that is starting from 0.
Creating arrays
• You can use array() function to create array.
• Syntax: $array_name=array ( value1, value2 …valueN);
• There are two ways to create indexed arrays.
• The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
• The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Length of an Array
• The count() function is used to return the length (the number of elements) of an array.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Accessing Array Elements
• The print_r() function is used to print information about a variable.
<?php
$myarray=array("A","B","C");
print_r($myarray);
?>
• You can refer to individual element of an array in PHP script using its key value as shown below:
<?php
$myarray=array("A","B","C");
echo $myarray[1];
?>
Output:
B
• In Numeric Array you can use for, while or do while loop to iterate through each element in array because
in numeric array key values are consecutive.
PAREPARED BY : TWINCLE VYAS
<?php
$myarray=array("Apache", "MySQL", "PHP");
for($i=0;$i<3;$i++)
{ echo $myarray[$i]."<br>"; }
?>
Output: Apache MySQL PHP
Changing Elements
• You can also change value of element using index.
<?php
$myarray=array("Apache", "MySQL", "PHP");
$myarray[1]="Oracle";
for($i=0;$i<3;$i++)
{
echo $myarray[$i]."<br>";
}
?>
Output: Apache Oracle PHP
Add elements to array
• The array_push() function inserts one or more elements to the end of an array.
• Syntax: array_push(array,value1,value2...)
✓ array: Required. Specifies an array
✓ value1: Required. Specifies the value to add
✓ value2: Optional. Specifies the value to add
<?php
$myarray=array("Apache", "MySQL", "PHP");
print_r($myarray);
echo "<br>";
$myarray[]="Oracle"; print_r($myarray);
echo "<br>";
array_push($myarray,"Java",".Net");
print_r($myarray);
?>
Output:
Array ( [0] => Apache [1] => MySQL [2] => PHP ) Array ( [0] => Apache [1] => MySQL [2] => PHP [3]
=> Oracle )
Array ( [0] => Apache [1] => MySQL [2] => PHP [3]
=> Oracle [4] => Java [5] => .Net )
Remove Element
• Unset () is used to destroy a variable in PHP. It can be used to remove a single variable, multiple variables,
or an element from an array.
• Syntax: unset (var1, var2....)
✓ var1, var2: The variable to be unset.
<?php
$cars = array("Volvo", "BMW", "Toyota", "35"=>"Maruti");
PAREPARED BY : TWINCLE VYAS
print_r($cars);
unset($cars[0]);
unset($cars["35"]);
echo "<br>"; print_r($cars);
?>
Output:
Array ( [0] => Volvo [1] => BMW [2] => Toyota [35]=> Maruti )
Array ( [1] => BMW [2] => Toyota )
Searching element
• The array_search() function search an array for a value and returns the key.
• Syntax: array_search(value,array,strict)
✓ value: Required. Specifies the value to search for
✓ array: Required. Specifies the array to search in
✓ strict: Optional. If this parameter is set to TRUE, then this function will search for identical elements in
the array.
<?php
$a=array("A"=>"5","B"=>5);
echo array_search(5,$a);
echo array_search(5,$a,true);
?>
Output:
AB
• The in_array() function searches an array for a specific value.
• Syntax: in_array(search,array,type)
✓ search: Required. Specifies the what to search for
✓ array: Required. Specifies the array to search
✓ type: Optional. If this parameter is set to TRUE, the in_array() function searches for the specific type in
the array.
<?php
$people=array("Peter", "Joe", "Glenn", 23);
if (in_array("23",$people))
{
echo "Match found<br>";
}
Else
{
echo "Match not found<br>";
}
if (in_array("23", $people, TRUE))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
PAREPARED BY : TWINCLE VYAS
}
?>
Output:
Match found Match not found
Sorting array
• 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
<?php
$srtArray=array(2,8,9,5,6,3);
for ($i=0; $i<count($srtArray); $i++)
{
for ($j=0; $j<count($srtArray); $j++)
{
if ($srtArray[$j] > $srtArray[$i])
{
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
foreach($srtArray as $item)
{ echo $item."<br>\n"; }
?>
Output:
235689
}
}
}
• Sort array using function.
<?php
$srtArray=array(2,8,9,5,6,3);
sort($srtArray);
foreach($srtArray as $item)
{
echo $item."<br>\n";
}
?>
Output:
235689
Associative Array
• The associative part means that arrays store element values in association with key values rather than in a
strict linear index order.
PAREPARED BY : TWINCLE VYAS
• If you store an element in an array, in association with a key, all you need to retrieve it later from that
array is the key value.
• Key may be either numeric or string.
• You can use array() function to create associative array.
• Syntax: $array_name=array(key1=>value1, key1=>value1,….. keyN=>valueN);
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
OR
$age["Peter"] = "35";
$age["Ben"] = "37";
$age["Joe"] = "43";
• You can refer to individual element of an array in PHP using its key value.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Ben:".$age["Ben"];
?>
Output:
Ben:37
• In associative array you cannot use for, while or do…while loop to iterate through each element in array
because in Associative array key value are not consecutive.
• So you have to use foreach loop.
<?php
$myarray=array("Name"=>"James", "Age"=>25, "Gender"=>"Male");
foreach($myarray as $item)
{ echo $item."<br>"; }
?>
Output: James 25
Male
Multidimensional Array
• Earlier, we have described arrays that are a single list of key/value pairs.
• However, sometimes you want to store values with more than one key.
• This can be stored in multidimensional arrays.
• A multidimensional array is an array containing one or more arrays.
• PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
• Example:
<?php
$cars = array
( array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
);
for ($row = 0; $row < 4; $row++)
{ echo "<br>";
for ($col = 0; $col < 3; $col++)
{ echo $cars[$row][$col]." "; }
}
?>
PAREPARED BY : TWINCLE VYAS
Output:
Volvo 22 18
BMW 15 13
Saab 5 2
User Defined Functions
• Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Create a User Defined Function
• A user defined function declaration starts with the word "function".
• Syntax:
function functionName()
{ Code to be executed; }
• Example:
<?php
function writeMsg()
{ echo "Hello world!"; }
writeMsg(); // call the function
?>
Output:
Hello world!
Function Arguments and returning values from function
• Information can be passed to functions through arguments. An argument is just like a variable.
• Arguments are specified after the function name; inside the parentheses separate with comma.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$result=addFunction(10, 20);
echo "Addition=".$result;
?>
Output:
Addition=30
Default values for arguments
• You can specify default values for arguments.
• If the argument is omitted from the function call the default is used.
• The default value must be a constant expression such as a string, integer or NULL.
PAREPARED BY : TWINCLE VYAS
• You can have multiple arguments with default values. Default values assign from right to left.
<?php
function addFunction($num1, $num2=5)
{
$sum = $num1 + $num2;
return $sum;
}
$result=addFunction(10,20); echo "Addition=".$result."<br>";
$result=addFunction(10); echo "Addition=".$result;
?>
Output: Addition=30 Addition=15
PAREPARED BY : TWINCLE VYAS