Module 1PHP
Module 1PHP
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 PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
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.
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive.
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>
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>
Multi-lines comments − They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary. The multiline style of commenting is the same as in C.
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
A statement in PHP is any expression that is followed by a semicolon (;).Any sequence of valid
PHP statements that is enclosed by the PHP tags is a valid PHP program. Here is a typical
statement in PHP, which in this case assigns a string of characters to a variable called $greeting −
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?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
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.
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
PHP automatically associates a data type to the variable, depending on its value. Since the data
types are not set in a strict sense, you can do things like adding a string to an integer without
causing an error.
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
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() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
OUTPUT
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
OUTPUT
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
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):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
OUTPUT: 15
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
OUTPUT: 15
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();
myTest();
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.
Note: The variable is still local to the function.
With PHP, there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command.
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
Display Variables
The following example shows how to output text and variables with the echo statement:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print .
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Display Variables
The following example shows how to output text and variables with the print statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
Variables can store data of different types, and different data types can do different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string can be any text inside quotes. You can use single or double quotes:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
<?php
$x = 5985;
var_dump($x);
?>
OUTPUT: int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
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.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.
Example
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
OUTPUT:
Null is a special data type which can have only one value: NULL.
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);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.
Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in
all scopes.
Some predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special.
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
Super global variables are built-in variables that are always available in all scopes.
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting
an HTML form.
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting
an HTML form with method="post". $_POST is also widely used to pass variables.
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
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.
The PHP comparison operators are used to compare two values (number or string):
PHP has two operators that are specially designed for strings.
The PHP conditional assignment operators are used to set a value depending on conditions:
PHP SETTYPE
Syntax
settype(variable, type);
Parameter Values
Parameter Description
type Required. Specifies the type to convert variable to. The possible types are:
boolean, bool, integer, int, float, double, string, array, object, null
<?php
$a = "32"; // string
settype($a, "integer"); // $a is now integer
$b = 32; // integer
settype($b, "string"); // $b is now string
$c = true; // boolean
settype($c, "integer"); // $c is now integer (1)
?>
GETTYPE
Syntax
gettype(variable);
<?php
$a = 3;
echo gettype($a) . "<br>";
$b = 3.2;
echo gettype($b) . "<br>";
$c = "Hello";
echo gettype($c) . "<br>";
$d = array();
echo gettype($d) . "<br>";
$f = NULL;
echo gettype($f) . "<br>";
$g = false;
echo gettype($g) . "<br>";
?>
TYPECASTING in PHP
In type casting, the compiler automatically changes one data type to another one depending on
what we want the program to do. For instance, in case we assign a float variable (floating point)
with an integer (int) value, the compiler will ultimately convert this int value into the float value.
Example:
<?php
// PHP program to show
// standard type casting
$a = 1;
var_dump($a);
// int to float
$a = (float) $a;
var_dump($a);
// float to double
$a = (double) $a;
var_dump($a);
// double to real
$a = (real) $a;
var_dump($a);
?>
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
Syntax
if (condition) {
code to be executed if condition is true;
}
<?php
$t = date("H");
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<?php
$t = date("H");
The if...elseif...else statement executes different codes for more than two conditions.
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;
}
<?php
$t = date("H");
Use the switch statement to select one of many blocks of code to be executed.
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;
}
<?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!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.
Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Syntax
while (condition is true) {
code to be executed;
}
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
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.
<?php
$colors = array("red", "green", "blue", "yellow");
PHP Break
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
Output
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.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Output
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.
Syntax
function functionname(){
//code to be executed
}
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
We can pass the information in PHP function through arguments which is separated by comma.
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?> Output:
Hello Sonoo
Hello Vimal
Hello John
Value passed to the function doesn't modify the actual value by default (call by value). But we
can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need
to use ampersand (&) symbol before the argument name.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
Output:
Cube of 3 is: 27
PHP Variable Length Argument Function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
Output:
10
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Example 1: Printing number
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>
Output:
1
2
3
4
5
echo factorial(5);
?>
Output:
120