PHP Programming Lo1 l4 SWD - Notes
PHP Programming Lo1 l4 SWD - Notes
SJITC: L4 SOD
TRAINER: MANIRARORA JMV
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
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 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
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.
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:
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
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!";
?>
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.
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
?>
22 | P a g e
Note:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
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.
$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).
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 :
<?php
$x = 5;
$y = 4;
25 | P a g e
echo $x + $y;
?>
Example3:
<!DOCTYPE html>
<html>
<body>
<?php
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print $x + $y;
?>
</body>
</html>
Output
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.
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:
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
For example:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array 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
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
echo $x ** $y;
?>
</body>
</html
Output: 1000
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
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.
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
The PHP logical operators are used to combine conditional statements. These are basically
used to operate with conditional statements and expressions.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = 50;
}
33 | P a g e
?>
</body>
</html>
Output:
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.
Examples:
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$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
35 | P a g e
Example1:
Output:
Array ( [a] => red [b] => green [c] => blue [d] => yellow )
Example2:
Output: bool(false)
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.
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
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
1. PHP String
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
37 | P a g e
Rules for integers:
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
$x = true;
$y = false;
38 | P a g e
Booleans are often used in conditional testing.
5. PHP Array
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.
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();
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);
?>
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).
<?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
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
$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:
41 | P a g e
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
<?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:
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):
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.
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
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.
44 | P a g e
Syntax:
Parameters:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
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();
?>
1. single-line
To write a single-line comment either start the line with either two slashes (//) or a hash
symbol (#).
For example:
<?php
?>
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:
<?php
/*
one line
*/
?>
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain
event occurred.
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:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.
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
Here are some characters that are commonly used for times:
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!
Examples:
Output: HelloWorld!
49 | P a g e
Output: John Carter!
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.
50 | P a g e
1. PHP - The if Statement
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");
b)
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
51 | P a g e
?>
Output:
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");
<?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");
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.
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>
<?php
if(isset($_POST['submit'])) {
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:
64 | P a g e
?>
65 | P a g e