0% found this document useful (0 votes)
23 views

Module 1PHP

Uploaded by

AJAY ROCK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Module 1PHP

Uploaded by

AJAY ROCK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

MODULE 1

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.

What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases

 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>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

PHP Case Sensitivity

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

# This is also 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.

Syntax for multiple-line comments:

<!DOCTYPE html>
<html>
<body>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

Statements are expressions terminated by semicolons

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 −

$greeting = "Welcome to PHP!";


PHP Variables

Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

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).

Rules for PHP variables:

 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 is a Loosely Typed Language

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.

PHP 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:

 local
 global
 static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

Variable with global scope:

<?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();

echo "<p>Variable x outside function is: $x</p>";


?>

OUTPUT

Variable x inside function is:

Variable x outside function is: 5


A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:

Variable with local scope:

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

OUTPUT

Variable x inside function is: 5

Variable x outside function is:

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.

PHP The global Keyword

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.

The example above can be rewritten like this:

<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

OUTPUT: 15

PHP The static Keyword

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.

PHP echo and print Statements

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 PHP echo Statement

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;

echo "<h2>" . $txt1 . "</h2>";


echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>

The PHP print Statement

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;

print "<h2>" . $txt1 . "</h2>";


print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>

PHP Data Types

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

 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:
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

PHP Integer

An integer data type is a non-decimal

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation

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

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.

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.

A class is a template for objects, and an object is an instance of a class.

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 . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

OUTPUT:

My car is a black Volvo!


My car is a red Toyota!

PHP NULL Value

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.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

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.

A common example of using the resource data type is a database call.


PHP Global Variables – Superglobals

Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in
all scopes.

PHP Global Variables - Superglobals

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.

The PHP superglobal variables are:

 $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".

$_GET can also collect data sent in the URL.

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.
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

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.

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

And, or, not Are examples of logical operators.

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1


and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

PHP Array Operators

The PHP array operators are used to compare arrays.


Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of the same
types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

PHP SETTYPE

The settype() function converts a variable to a specific type.

Syntax
settype(variable, type);
Parameter Values
Parameter Description

variable Required. Specifies the variable to convert

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

The gettype() function returns the type of a variable.

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>";

$e = array("red", "green", "blue");


echo gettype($e) . "<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);
?>

Flow Control statements In PHP

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

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:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Syntax
if (condition) {
code to be executed if condition is true;
}

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

PHP - The if...else Statement

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");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif...else Statement

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");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The switch Statement

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.

In PHP, we have the following loop types:

 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

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;
}

<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

The PHP do...while Loop

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 PHP for Loop

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:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

The PHP foreach Loop

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");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

PHP Break

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:

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>

Output

The number is: 0


The number is: 1
The number is: 2
The number is: 3

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
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

Output

The number is: 0


The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9

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.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Syntax

function functionname(){
//code to be executed
}

<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?> Output:
Hello Sonoo
Hello Vimal
Hello John

PHP Call By Reference

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:

Hello Call By Reference

PHP Function: Default Argument Value

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

PHP Function: Returning Value


<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

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;
}

echo add(1, 2, 3, 4);


?>

Output:

10

PHP Recursive Function

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

Example 2 : Factorial Number


<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}

echo factorial(5);
?>

Output:

120

You might also like