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

PHP Programming Lo1 l4 SWD - Notes

Uploaded by

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

PHP Programming Lo1 l4 SWD - Notes

Uploaded by

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

RQF LEVEL 4

SJITC: L4 SOD
TRAINER: MANIRARORA JMV

MODULE CODE: SWDPP401

Handouts
Module name: PHP PROGRAMMING
2|Page
3|Page
4|Page
5|Page
Learning outcome 1: Apply PHP Fundamentals
1.1. Preparation of PHP Programming environment

 Definition of key terms

PHP: PHP is a server side scripting language that is used to develop Static websites or
Dynamic websites or Web applications.
 PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home
Pages.
 PHP scripts can only be interpreted on a server that has PHP installed.
 The clients’ computers accessing the PHP scripts require a web browser only.
 A PHP file contains PHP tags and ends with the extension ".php"
 PHP is an interpreted language, i.e. there is no need for compilation.

 PHP is an object-oriented language.

 PHP is an open-source scripting language.

 PHP is simple and easy to learn.

PHP was created by Rasmus Lerdorf in 1994 but appeared on the market in 1995. PHP 7.4.0 is
the latest version of PHP, which was released on 28 November.

Interpreter: Is a program that translates the entire source code line by line into machine
language.

Compiler: Is a program that translates the entire source code in a single run into machine

code/language.

6|Page
Notes: The difference between interpreter and compiler

Interpreter Compiler
Is a program that translates the entire Is a program that translates the entire
source code line by line into machine source code in a single run into machine
language code/language.
A program that executes instructions A program that translates source code into
written in a high-level language (it directly object code.
executes the instructions in a high-level It is a program which translates the human-
language, without converting it into readable code to a language a computer
machine). processor understands (binary 1 and 0 bits)=
Compiling is the process of transforming a
high level language into a low level
language.
It consumes much time than compiler It consumes less time means it is faster than
interpreter
CPU utilization is less CPU utilization is more
Localization of errors is easy Localization of errors is difficult
It is used by the languages such as: Java, It is used by the languages such as: C,
Python, Ruby, Perl, PHP etc. C++,C#, etc.

Open Source: In programming, "open source" refers to software or projects whose source
code is made available to the public, typically under an open-source license. This means
that anyone can view, use, modify, and distribute the source code of the software freely.

Web Server: is software and hardware that uses HTTP (Hypertext Transfer protocol) and
other protocols to respond to client requests made over the World Wide Web. The main
job of a web server is to display website content through storing, processing and
delivering webpages to users.

7|Page
Apache: is the web server that processes requests and serves web assets and content via
HTTP.
 Is the most popular web server in the world developed by the Apache Software
Foundation. Apache web server is open source software and can be installed on almost
all operating systems including Linux, Unix, Windows, FreeBSD, Mac OS and more.
About 60% of the web server machines run the Apache Web Server.
Database: is an organized collection of data, so that it can be easily accessed and
managed.
DBMS: is a software which is used to manage the database. For example: MySQL, Oracle,
etc.
 DBMS provides an interface to perform various operations like database creation,
storing data in it, updating data, creating a table in the database and a lot more.
 It provides protection and security to the database. In the case of multiple users,
it\also maintains data consistency.
MySQL: MySQL is an open-source relational database management system (RDBMS) that
is widely used for managing and storing structured data.
Static website: is a set of web pages whose content remains the same whenever
visitors access it. This site is built with HTML, CSS, and JavaScript without server -side
scripting language.
Dynamic website: is a collection of dynamic web pages whose content changes
dynamically. It accesses content from a database or Content Management System (CMS).

8|Page
9|Page
 Purpose of PHP

 PHP is a general-purpose scripting language that is especially suited to server-side web


Development, in which case PHP generally runs on a web server.
 PHP can help to collect form data, generate dynamic page content, or send and receive
cookies.
 One of the important advantages of PHP is that it is Open Source. Therefore, PHP is
readily available and is entirely free. In contrast to other scripting languages used for
web development which requires the user to pay for the support files, PHP is open to
everyone, anytime and anywhere.

 Important characteristics of PHP


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
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side = Simple, Familiar and ease
of use.
PHP is loosely typed language: PHP encourages the use of variables without declaring
its data types.

PHP is Object-oriented interpreted language.

 PHP Development Tools

 XAMPP
 WAMP/MAMP/LAMP
 IDEs /Text Editors
 Browser

10 | P a g e
1. XAMPP

XAMPP is an acronym, in which "X" stands for Multiplatform, "A" stands for Apache server,
"M" stands for MariaDB, "P" stands for Perl, and "P" stands for PHP.

 It is a stack of software, which includes Apache distributions used to develop and test
website locally before its deployment on the internet.
 It is multiplatform and is supported by many operating systems such as Windows,
MacOS, and Linux.
 The XAMPP server software on a local computer provides an appropriate environment
for testing MYSQL, PHP, Apache, and Perl projects.

2. WAMP

WAMP is another local server, which is a package of software including Apache Server (which
stands for A), MySQL database (which stands for M), and PHP script-based language (which
stands for P). The "W" in WAMP designates its exclusiveness for the Windows Operating
system. WAMP is used in Windows-based systems to test dynamic websites without
publishing it on the webserver. It is handy to implement and developed with PHP.

3. MAMP

11 | P a g e
MAMP is a local server, which is compatible with Mac Operating system and supports
development & testing of web projects based on (A) Apache Server, (M) MySQL Database and
(P) PHP OOPS based programming language. It provides all the equipment that is needed to
run WordPress on the system.

4. Text Editors and IDEs

 IDE’s are the software designed for developers to write the code in an efficient way. It
stands for Integrated Development Environment. With the help of IDE’s, we can write,
modify, compile, execute, test and debug the code easily with a single software. Some
IDEs contain a compiler, interpreter, or both.

Many IDE’s support the auto-suggestions and the auto correction which makes the
developer to code easier.

EXAMPLES:

 Microsoft visual studio


 PyCharm
 Aptana Studio 3
 DbVisualizer
 NetBeans
 Eclipse
 Anjuta DevStudio
 Code::Blocks
 Zend Studio
 Komodo
 Text/Code Editors: (are systems or programs that allow users/programmers to edit
texts), are similar to IDE’s but in a Text editor you can only write and Modify the code,
but when it comes to run the code you need to open the command prompt. It provides
fewer features than IDE.

12 | P a g e
EXAMPLES:
 Microsoft Visual Studio Code
 Notepad++
 Sublime text
 Atom
 Brackets
 Vim
 UltraEdit
 BBEdit
 GNU Emacs
 EditPlus
 BlueFish Editor
 TextPad
 Gedit
 Komodo Edit
5. BROWSER

A browser is an application program that provides a way to look at and interact with all the
information on the World Wide Web.

EXAMPLES:

 Mozilla firefox
 Google chrome
 Safari
 Opera
 Internet explorer
 Microsoft edge
 Netscape navigator
 Brave
 Vivaldi
 Chromium
 Tor browser
 Maxthon
 Yandex browser
 Lynx
 Epix
 Seamonkey
 UC browser
 Opera mini

13 | P a g e
 Installation of XAMPP/WAMP or LAMP

Installation process of XAMPP === the installation process in Windows

STEP 1- Open any web browser and visit https://www.apachefriends.org/index.html. On the


home page, you can find the option to download XAMPP for three platforms- Windows, MAC,
and Linux. Click on XAMPP for Windows. The latest version available on the website is 7.4.5.

As soon as you click on it, a message displaying the automatic start of download appears on
the screen.

STEP 2- After the download is completed, double click the .exe extension file to start the
process of installation

14 | P a g e
STEP 3- A pop-up screen with the message asking you to allow to make changes on your
desktop appears. Click "YES" to continue the process.

STEP 4- Click to allow access or deactivate the firewall and any other antivirus software
because it can hamper the process of installation. Thus, it is required to temporarily disable
any antivirus software or security firewall till the time all the XAMPP components have been
installed completely.

15 | P a g e
STEP 5- Just before the installation, a pop-up window appears with a warning to disable UAC.
User Account Control (UAC) interrupts the XAMPP installation because it restricts the access
to write to the C: drive. Therefore, it is suggested to disable it for the period of installation.

STEP 6- After clicking the .exe extension file, the XAMPP setup wizard opens spontaneously.
Click on "NEXT" to start the configuration of the settings.

16 | P a g e
STEP 7- After that, a 'Select Components' panel appears, which gives you the liberty to choose
amongst the separate components of the XAMPP software stack for the installation. To get a
complete localhost server, it is recommended to install using the default options of containing
all available components. Click "NEXT" to proceed further.

17 | P a g e
STEP 8- The setup is now ready to install, and a pop-up window showing the same appears on
the screen. Click "NEXT" to take the process forward.

18 | P a g e
STEP 9- Select the location where the XAMPP software packet needs to be installed. The
original setup creates a folder titled XAMPP under C:\ for you. After choosing a location, click
"NEXT".

STEP 10- After choosing from all the previously mentioned preferences (like language and
learn more bitnami dialogue box) click to start the installation. The setup wizard will unpack
and install the components to your system. The components are saved to the assigned
directory. This process may takes a few minutes to complete. The progress of the installation
in terms of percentage is visible on the screen.

19 | P a g e
STEP 11- After the successful installation of the XAMPP setup on your desktop, press the
"FINISH" button.

20 | P a g e
On clicking the FINISH button, the software automatically launches, and the CONTROL PANEL
is visible. The image below shows the appearance of the final result.

21 | P a g e
1.2. Application of PHP concepts
 Topic 1: PHP file extension

In PHP, the file extension for PHP scripts is typically ".php". When you create a PHP script, you
should save it with this file extension so that the web server recognizes it as a PHP file and
processes it accordingly.

For example, if you create a PHP script to display "Hello, World!", you would save it with a
".php" extension, such as "hello.php".

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

 What Is a PHP File Extension?

The term .php file extension refers to the name of a file with a PHP script or source code that
has a ".php" extension at the end of it. It is similar to a Word file with a .doc file extension.

 Topic2 : PHP Syntax

Basic PHP Syntax

A PHP script starts with <?php and ends with ?>. These tags are also called ‘Canonical PHP
tags’. Everything outside of a pair of opening and closing tags is ignored by the PHP parser.
The open and closing tags are called delimiters.

<?php

// PHP code goes here

?>

22 | P a g e
Note:

A PHP script can be placed anywhere in the document


PHP statements end with a semicolon (;)

The default file extension for PHP files is ".php"


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>

 Topic 3: PHP Variables

Definition: A variable in PHP is a name of memory location that holds data. The variables
are also like containers that store character values, numeric values, memory addresses, and
strings in a program.

Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.

Syntax of declaring a variable in PHP is given below:

$variablename = value;

23 | P a g e
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.

Notes:

When you assign a text value to a variable, put quotes around the value.
Unlike other programming languages, PHP has no command for declaring a variable.
It is created the moment you first assign a value to it.
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for PHP variables:

 Any variables declared in PHP must begin with a dollar sign ($), followed by the
variable name.
 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 alphanumeric characters and underscores (i.e., ‘a-
z’, ‘A-Z’, ‘0-9, and ‘_’) in their name.
 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 PHP print statement also is similar to the echo statement and can be used
alternative to echo many times.

24 | P a g e
The difference between echo and print

The following example will show how to output text and a variable:

Example1:

<?php
$txt = "software development";
echo "I love $txt!";
?>

The following example will produce the same output as the example above:

<?php
$txt = " software development ";
echo "I love " . $txt . "!";
?>

Example2 :

The following example will output the sum of two variables:

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

25 | P a g e
echo $x + $y;
?>

Example3:

<!DOCTYPE html>

<html>

<body>

<?php

$txt1 = "Learn PHP";

$txt2 = "W3Schools.com";

$x = 5;

$y = 4;

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

print "Study PHP at " . $txt2 . "<br>";

print $x + $y;

?>

</body>

</html>

Output

Study PHP at W3Schools.com


9

PHP is a Loosely Typed Language

PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analysing the values. The same happens
while conversion. No variables are declared before they are used. It automatically converts
types from one type to another whenever required.

26 | P a g e
In other languages such as C, C++, and Java, the programmer must declare the name and type
of the variable before using it.

PHP Variable: Declaring string, integer and float

Let's see the example to store string, integer and float values in PHP variables.

File: variable1.php

<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>

Output:

string is: hello string


integer is: 200
float is: 44.6

PHP Variables are: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.

File: variable3.php

<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

27 | P a g e
Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

 Topic 4: PHP Operators

PHP Operator is a symbol which is used to perform operations on operands.


Operators are used to perform operations on variables and values.

For example:

$num=10+20; //+ is the operator and 10,20 are operands

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

1. PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

28 | P a g e
OPERATOR NAME EXAMPLE RESULT

+ Addition $x + $y Sum of $x and $y


- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y


/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power


(Introduced in PHP 5.6)

Example:

<!DOCTYPE html>

<html>

<body>

<?php

$x = 10;

$y = 3;

echo $x ** $y;

?>

</body>

</html

Output: 1000

2. PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable
(These operators are used to assign values to different variables, with or without mid-
operations). 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.

29 | P a g e
OPERATOR NAME SYNTAX OPERATION
= Assign $x = $y Operand on the left obtains the value
of the operand on the right
+= Add then Assign $x += $y Simple Addition same as $x = $x + $y
-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x –
$y
*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
/= Divide then Assign (quotient) $x /= $y Simple division same as $x = $x / $y
%= Divide then Assign (remainder) $x %= $y Simple division same as $x = $x % $y

Example:

<!DOCTYPE html>

<html>

<body>

<?php

$x = 20;

$x += 100;

echo $x;

?>

</body>

</html>

Output: 120

3. PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string): These
operators are used to compare two elements and outputs the result in Boolean form.

30 | P a g e
OPERATOR NAME EXAMPLE RESULT
== Equal $x = = $y Returns true if $x is equal to $y
=== Identical $x = = = $y Returns true if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x < > $y Returns true if $x is not equal to $y
!= = Not $x !== $y Returns true if $x is not equal to $y, or they are not
identical of the same type
> Greater $x > $y Returns true if $x is greater than $y
than
< Less than $x < $y Returns true if $x is less than $y
>= Greater $x >= $y Returns true if $x is greater than or equal to $y
than or
equal to
<= Less than or $x <= $y Returns true if $x is less than or equal to $y
equal to
Example:

<!DOCTYPE html>

<html>

<body>

<?php

$x = 100;

$y = "100";

var_dump($x === $y); // returns false because types are not equal

?>

</body>

</html>

Output: bool(false)

31 | P a g e
4. 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.

OPERATOR NAME DESCRIPTION


++$x Pre- Increments $x by one, then returns $x
increment
$x++ Post- Returns $x, then increments $x by one
increment
- -$x Pre- Decrements $x by one, then returns $x
decrement
$x-- Post- Returns $x, then decrements $x by one
decrement

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$x = 10;

echo ++$x;

?>

</body>

</html>

Output: 11

<!DOCTYPE html>

<html>

<body>

<?php

32 | P a g e
$x = 10;

echo $x++;

?>

</body>

</html>

Output: 10

5. PHP Logical or Relational Operators:

The PHP logical operators are used to combine conditional statements. These are basically
used to operate with conditional statements and expressions.

OPERATOR NAME SYNTAX OPERATION


and Logical AND $x and $y True if both the operands are true else false
or Logical OR $x or $y True if either of the operands is true else false
xor Logical XOR $x xor $y True if either of the operands is true and false if
both are true
&& Logical AND $x && $y True if both the operands are true else false
|| Logical OR $x || $y True if either of the operands is true else false
! Logical NOT !$x True if $x is false
Example:

<!DOCTYPE html>

<html>

<body>

<h1>The and Operator</h1>

<p>Write a message if both conditions are true.</p>

<?php

$x = 100;

$y = 50;

if ($x == 100 and $y == 50) {

echo "Hello world!";

}
33 | P a g e
?>

</body>

</html>

Output:

6. PHP String Operators

PHP has two operators that are specially designed for strings. This operator is used for the
concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use
the concatenating assignment operator (‘.=’) to append the argument on the right side to
the argument on the left side.

OPERATOR NAME SYNTAX OPERATION

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns,


.= $x.=$y
assignment same as $x = $x.$y

Examples:

<!DOCTYPE html>

<html>

<body>

<?php

$txt1 = "Hello";

$txt2 = " world!";

$txt1 .= $txt2;

34 | P a g e
echo $txt1;

?>

</body>

</html>

Output:

Hello world!

<?php
$name="John";
$lastName="Travolta";
echo $name." ".$lastName; // Outputs John Travolta
$a="Hello";
$a .= " John!";
echo $a; // Outputs Hello John!
?>
7. 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- $x !== $y Returns true if $x is not identical to $y
identity

35 | P a g e
Example1:

Output:

Array ( [a] => red [b] => green [c] => blue [d] => yellow )

Example2:

Output: bool(false)

 Topic 5: PHP Data Types

Data Types define the type of data a variable can store. PHP allows eight different types of
data types. All of them are discussed below. There are pre-defined, user-defined, and
special data types.

The predefined data types are:

 Boolean
 Integer
 Double
 String

36 | P a g e
The user-defined (compound) data types are:

 Array
 Objects
The special data types are:

 NULL
 Resource

Notes: So, PHP supports the following data types in general:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

1. 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;
?>

2. PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

37 | P a g e
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 three formats: decimal (10-based), hexadecimal (16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)

In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:

Example

<?php
$x = 5985;
var_dump($x);
?>

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

Example

<?php
$x = 10.365;
var_dump($x);
?>

4. PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;

38 | P a g e
Booleans are often used in conditional testing.

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

Example

<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

6. PHP Object

An object is a data type, which stores data and information on how to process that data.

In PHP, an object must be explicitly declared.

First, we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods:

Example

<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();

// show object properties


echo $herbie->model;
?>
39 | P a g e
7. 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);
?>

8. 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 (Resource variables typically hold special handlers for opened
files and database connections).

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

<?php
// connect to MySQL database server with default setting
$link = mysqli_connect("localhost", "root", "");
var_dump($link);
?>

40 | P a g e
 Topic 6: Php Variable 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:

Example: Global variable

<?php
$name = "Harry Bhai"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>

Output:

Variable inside the function: Harry Bhai


Variable outside the function: Harry Bhai

41 | P a g e
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:

Example: local variable

<?php
function mytest()
{
$capital = "Delhi";
echo "Capital of India is: " .$capital;
}
mytest(); //Calling the function
//using $capital outside the function will generate an error
echo $capital;
?>

Output:

Capital of India is: Delhi

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

Example

<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;

42 | P a g e
}
myTest();
echo $y; // outputs 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:

Example:

<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?

Static Variable:

PHP has a feature that deletes the variable once it has finished execution and frees the
memory. When we need a local variable which can store its value even after the execution,
we use the static keyword before it and the variable is called static variable. These variables
only exist in a local function and do not get deleted after the execution has been completed.

For Example:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable

43 | P a g e
//increment in non-static variable which will increment its value to 7
$num1++;
//increment in static variable which will increment its value to 4 after first
execution and 5 after second execution
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
//first function call
static_var();
//second function call
static_var();
?>

Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

 Topic 7: 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.

Create a PHP Constant

To create a constant, use the define() function.

44 | P a g e
Syntax:

define(name, value, case-insensitive)

Parameters:

 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-sensitive name:

Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

The example below creates a constant with a case-insensitive name:

Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>

Constants are Global

Constants are automatically global and can be used across the entire script.

The example below uses a constant inside a function, even if it is defined outside the
function:

45 | P a g e
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>

 Topic 8: PHP Comments

A comment is simply text that is ignored by the PHP engine.

The purpose of comments is to make the code more readable.


PHP comments can be used to describe any line of code so that other developer can
understand the code easily.
It can also be used to hide any code.
We use comments to understand the functionality of the codes in a program.

Types of PHP comments

PHP support single-line as well as multi-line comments.

1. single-line

To write a single-line comment either start the line with either two slashes (//) or a hash
symbol (#).

For example:

Run this code »

<?php

// This is a single line comment

# This is also a single line comment

echo "Hello, world!";

?>
46 | P a g e
2. multi-line comments

However to write multi-line comments, start the comment with a slash followed by an
asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:

Example:

Run this code »

<?php

/*

This is a multiple line comment block

that spans across more than

one line

*/

echo "Hello, world!";

?>

 Topic 9: PHP date and time

The PHP date() function is used to format a date and/or a time.

The PHP date() function formats a timestamp to a more readable date and time.

Syntax
date(format,timestamp)

Parameter Description

format Required. Specifies the format of the timestamp

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.

47 | P a g e
Get a Simple 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:

 d - Represents the day of the month (01 to 31)


 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
 l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.

The example below formats today's date in three different ways:

Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
PHP Tip - Automatic Copyright Year

Use the date() function to automatically update the copyright year on your website:

Example

&copy; 2010-<?php echo date("Y");?>


Get a Simple Time

Here are some characters that are commonly used for times:

 h - 12-hour format of an hour with leading zeros (01 to 12)


 i - Minutes with leading zeros (00 to 59)
 s - Seconds with leading zeros (00 to 59)
 a - Lowercase Ante meridiem and Post meridiem (am or pm)

48 | P a g e
The example below outputs the current time in the specified format:

Example
<?php
echo "The time is " . date("h:i:sa");
?>
Note that the PHP date() function will return the current date/time of the server!

 Topic 10: PHP String Concatenation


There are two string operators. The first is the concatenation operator (‘.‘), which returns
the concatenation of its right and left arguments. The second is the concatenating
assignment operator (‘.=‘), which appends the argument on the right side to the argument
on the left side.

Examples:

Output: HelloWorld!

49 | P a g e
Output: John Carter!

 Topic 11: PHP Conditional Statements

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:

 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
 nested if Statement- The nested if statement contains the if block inside
another if block. The inner if statement executes only when specified condition
in outer if statement is true.
 switch statement - selects one of many blocks of code to be executed

50 | P a g e
1. 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;
}

Flowchart

Examples:

a) The example below will output "Have a good day!" if the current time (HOUR) is less
than 20:

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

if ($t < "20") {


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

b)

<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}

51 | P a g e
?>

Output:

12 is less than 100

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

Flowchart

Examples:
Example1: The example below will output "Have a good day!" if the current time is less than
20, and "Have a good night!" otherwise:

52 | P a g e
<?php
$t = date("H");

if ($t < "20") {


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

<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>

Example3:
<?php
$a=10;
$b=20;
if ($a > $b)
echo "a is bigger than b";
else
echo "a is not bigger than b";
?>
3. PHP - The if...elseif....else Statement

The if....elseif...else statement executes different codes for more than two conditions.

Syntax:

53 | P a g e
Flowchart

Examples:

Example1: The example below will 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!"

54 | P a g e
<?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!";
}
?>

Example2:
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>

Output: B Grade

55 | P a g e
Example3:

<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "<h3>Have a nice weekend!</h3>";
elseif ($d == "Sun")
echo "<h3>Have a nice Sunday!</h3>";
else
echo "<h3>Have a nice day!</h3>";
?>
</body>
</html>
4. PHP nested if Statement

The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.

Syntax:

56 | P a g e
Flowchart:

Example:

Output:
Eligible to give vote

57 | P a g e
5. PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
The switch statement is used to perform different actions based on different
conditions.
The switch statement is used to avoid long blocks of if..elseif..else codes.

Syntax:

Or:

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

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case
58 | P a g e
in the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.

A special case is the default case. This case matches anything that wasn't matched by the
other cases.

PHP Switch Flowchart

59 | P a g e
Example1:

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

Example2:

60 | P a g e
Example3:
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body></html>

61 | P a g e
Example4: Switch Case in PHP with User Input

<form action=" " method="POST">

<label>Please Enter a number between 1 - 26</label>

<input type="text" name="number">

<input type="submit" name="submit">

</form>

<?php

// if the form has been submitted

if(isset($_POST['submit'])) {

$number = (int) $_POST['number'];

switch($number) {

case 1:

echo "A";

break;

case 2:

echo "B";

break;

case 3:

echo "C";

break;

case 4:

echo "D";

break;

case 5:

echo "E";

break;

case 6:

echo "F";

break;

case 7:

echo "G";

62 | P a g e
break;

case 8:

echo "H";

break;

case 9:

echo "I";

break;

case 10:

echo "J";

break;

case 11:

echo "K";

break;

case 12:

echo "L";

break;

case 13:

echo "M";

break;

case 14:

echo "N";

break;

case 15:

echo "O";

break;

case 16:

echo "P";

break;

case 17:

echo "Q";

break;

63 | P a g e
case 18:

echo "R";

break;

case 19:

echo "S";

break;

case 20:

echo "T";

break;

case 21:

echo "U";

break;

case 22:

echo "V";

break;

case 23:

echo "W";

break;

case 24:

echo "X";

break;

case 25:

echo "Y";

break;

case 26:

echo "Z";

break;

default:

echo 'wrong number';

64 | P a g e
?>

Let’s think about the below ideas:

65 | P a g e

You might also like