Chapter 1.
BASICS OF PHP
Learning Objectives:
After successful completion of this unit, you will be able to
1. Understand origin of PHP
2. Understand basics of PHP.
3. Summarize variables, constants and data types.
4. Summarize conditional statement in PHP.
5. Summarize built in functions in PHP.
This chapter will introduce you to PHP.
You will learn how it came about, what it looks like,
and why it is the best server-side technology. You will also be exposed to the most important
features of the language.
This chapter will let you poke around the different variables & constants, data types,
operators, decision making & loops, predefined functions in PHP.
1.1 Introduction:-
The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side
scripting language designed specifically for web development. PHP can be easily embedded
in HTML files and HTML codes can also be written in a PHP file. The thing that
differentiates PHP with client-side language like HTML is, PHP codes are executed on the
server whereas HTML codes are directly rendered on the browser. In our entire course we
will be studying PHP 7 version and on an Ubuntu OS.
The Origins of PHP
PHP began as a simple tool created by Rasmus Lerdorf to track visitors to his online resume and
embed SQL queries into web pages. Originally called Personal Home Page Tools (PHP 1.0), it
was shared freely on the web and quickly gained popularity.
As more developers adopted it, they requested additional features. In response, Lerdorf expanded
the language to include structured programming capabilities such as loops, conditionals, and
improved data handling. After studying parser tools like YACC and GNU Bison, he released
PHP 2.0.
PHP 2.0 allowed developers to embed structured code directly within HTML, process form data,
interact with databases, and perform complex calculations efficiently. Because it compiled into
the Apache web server, PHP scripts ran as part of the server process, avoiding the performance
issues commonly associated with CGI scripts.
By the mid-1990s, PHP had evolved into a legitimate development platform and began powering
commercial websites, including the SuperCuts site created by Clear Ink in 1996.
1.3 PHP Installation – Summary (LAMP Stack Setup)
The LAMP stack consists of:
Linux – Operating system
Apache HTTP Server – Web server
MySQL – Database system
PHP – Server-side scripting language
It is used to set up and run dynamic web servers.
Step 1: Prerequisites - You must have sudo privileges account access to the Linux system.
Login to your system and upgrade the current packages to the latest available version. sudo apt
update sudo apt upgrade Also, install the below packages on your system. sudo apt install ca-
certificates apt-transport-https
Step 2: Install Apache Web Server
In this step, we install a web server on your VPS. Although you can use Nginx, here we install
Apache HTTP Server, one of the most popular and widely used web servers in the world.
Install Apache
sudo apt-get install apache2
Start Apache
sudo systemctl start apache2
Enable Apache to Start at Boot
sudo systemctl enable apache2
Check Apache Status
sudo systemctl status apache2
Verify Installation
Open your web browser and enter your server’s IP address:
[Link]
If Apache is installed correctly, you will see the default Apache welcome page.
Step 3: Install MySQL
MySQL is a database management system used to store and retrieve data for your applications.
Install MySQL
sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
During installation, you will be prompted to set a root password.
Initialize MySQL
sudo mysql_install_db
Secure MySQL Installation
Run the security setup script:
sudo /usr/bin/mysql_secure_installation
Enter your current root password.
When asked to change the root password, you may choose N if you want to keep it.
It is recommended to answer Yes to all other security options.
After completion, MySQL will reload and apply the new security settings.
Step 4: Install PHP7 - PHP is an open source web scripting language that is widely used to
build dynamic webpages. To install PHP, open terminal and type in this command. sudo apt-get
install -y php7.0After completing these steps, your LAMP stack (Linux, Apache, MySQL, PHP)
will be successfully installed, allowing you to host and run dynamic websites on your server.
1.4 PHP Basic Syntax -PHP or Hypertext Preprocessor is a widely used open-source general
purpose scripting language and can be embedded with HTML. PHP scripts can be written
anywhere in the document within PHP tags along with normal HTML.
1.4.1 Writing PHP Statements-
A PHP statement tells PHP to perform an action.
1. Simple Statements
One of the most common PHP statements is echo, which displays output.
Example:
echo "Hi";
Everything inside the double quotes is displayed.
Simple statements must end with a semicolon (;).
PHP reads a statement until it finds a semicolon or a closing PHP tag.
PHP ignores whitespace (spaces and line breaks).
Another common output statement is print.
Example:
print "Hello world!";
print "I'm about to learn PHP!";
print can be written with or without parentheses: print or print().
Like echo, it must end with a semicolon.
2. Common Error: Missing Semicolon
Forgetting a semicolon causes a parse error, such as:
Parse error: expecting ',' or ';' in [Link] on line 6
Important note:
The error usually appears on the line after the actual mistake.
Using an editor that shows line numbers makes debugging easier.
Although PHP allows writing multiple statements on one line (separated by semicolons),
it is better to write each statement on a new line for readability.
3. Block Statements (Complex Statements)
Sometimes, multiple statements are grouped together in a block, enclosed in curly braces { }.
Example:
if ($time == "midnight") {
put on pajamas;
brush teeth;
go to bed;
}
All statements inside the braces execute together.
If the condition is true, all actions run.
If false, none of them run.
These are called complex statements (e.g., if statements).
Key Rules:
A semicolon is required inside the block after each simple statement.
No semicolon is needed after the closing curly brace }.
PHP reads the entire block before executing it.
4. Importance of Indentation
Indentation is not required by PHP.
It improves readability for humans.
Proper indentation helps prevent common mistakes like missing a closing curly brace.
Missing braces are especially hard to detect in nested blocks.
Conclusion
Simple statements end with a semicolon.
Output is commonly done using echo or print.
Complex statements use blocks {}.
Good formatting and indentation make scripts easier to read and debug.
1.4.2 Building Scripts- To build a script, you add PHP statements one after another to a file that
you name with a .php extension. Actually, if you are wise, you write the script on paper first,
unless the script is very simple or you are quite experienced. Planning makes programming much
less prone to [Link] you‘re writing a PHP script for your Web site, you insert the PHP
statements into the file that contains the HTML for your Web page. If you‘re writing a script that
will run independent of the Web, you type the PHP statements into a file and then you run the
script by calling PHP directly.
1.5 PHP Tags or Escaping To PHP -The mechanism of separating a normal HTML from PHP
code is called the mechanism of Escaping To PHP. There are various ways in which this can be
done. Few methods are already set by default but in order to use few others like Short-open or
ASP-style tags we need to change the configuration of [Link] file. These tags are also used for
embedding PHP within HTML. There are 4 such tags available for this purpose:-
1. Canonical PHP Tags: The script starts with . These tags are also called ‗Canonical PHP
tags‘. Every PHP command ends with a semi-colon (;).# Here echo command is used to print
Let‘s look at the hello world program in PHP:
<?php
echo "Hello, world!";
?>
Output: Hello, world!
2. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code.
The script starts with <? and ends with ?>. This will only work by setting the
short_open_tag setting in [Link] file to ‗on‘.
Example:
<?
# Here echo command will only work if
# setting is done as said before
echo "Hello, world!";
?>
3. HTML Script Tags: These are implemented using script tags. This syntax is
removed in PHP 7.0.0 so its no more used.
Example:
<script language="php">
echo "hello world!";
</script>
4. ASP Style Tags: To use this we need to set the configuration of [Link] file. These are
used by Active Server Pages to describe code blocks. These starts with <% and ends
with %>.
Example:
<%
# Can only be written if setting is turned on
# to allow %
echo "hello world";
%>
1.6Running a PHP script:For Linux/ Unix, if you have a file named [Link] containing this
PHP code, you can run it from the command line by having the file in the same directory where
PHP is installed and by typing the following:[Link]
Or you can type the entire path name to PHP, as in the following example:
/usr/local/php/cli/[Link]
The CLI version of PHP differs from the CGI version in the following ways:
The CLI (Command Line Interface) and CGI (Common Gateway Interface) versions of
PHP differ mainly in how they handle output and user interaction. The CGI version runs through
a web server and automatically sends HTTP headers and HTML-formatted error messages to the
browser. In contrast, the CLI version runs in the terminal, does not send HTTP headers, and
displays errors in plain text. Additionally, CLI provides argc and argv variables by default to
accept command-line arguments.
Key Differences
1️⃣ Output of HTTP Headers
CGI Version: Sends HTTP headers such as:
Content-type: text/html
X-Powered-By: PHP/7.0
These are required for communication between the web server and browser.
CLI Version: Does not send HTTP headers because it runs directly in the terminal.
2️⃣ Error Message Formatting
CGI Version: Errors are formatted using HTML (for browser display).
CLI Version: Errors are displayed in plain text.
3️⃣ argc and argv Variables
CLI Version: argc and argv are available by default to pass command-line arguments.
CGI Version: These variables are not available by default because user input usually
comes from web forms.
Example: Checking PHP Version in CLI
To check the installed PHP version using CLI:
php -v
This command displays the current version of PHP installed on the system.
Table 1.1 shows the most useful PHP command-line options.
Option Description Example
-c Define path to a specific [Link] php -c /usr/local/php/cli/[Link]
-f Identify script file to run php -f /myfiles/[Link]
-h Display help file php -h
-i Display PHP info in text php -i
-l Check script syntax without running php -l [Link]
-m List compiled PHP modules php -m
-r Run PHP code directly php -r 'print("Hi");'
-v Display PHP version php -v
1.7 Variables in PHP –
In PHP, a variable is a container used to store data such as numbers, text, or user input.
Variables allow programmers to save information and reuse it later in the script. They are
especially useful in web applications for storing form data, such as a user’s name or age. A
variable in PHP always begins with the dollar sign ($) followed by its name.
1.7.1 Naming Variables
PHP has specific rules for naming variables:
1. Every variable must start with a dollar sign ($).
2. The name can contain letters, numbers, and underscores (_).
3. The name must begin with a letter or an underscore (not a number).
4. Variable names are case-sensitive.
5. There is no limit to the length of a variable name.
✅ Valid Variable Names
$_name
$first_name
$name3
$name_3
❌ Invalid Variable Names
$3name // Cannot start with a number
$name? // Special character not allowed
$first+name // Special character not allowed
$[Link] // Dot not allowed
Important Note on Case Sensitivity
$favoriteCity = "Paris";
echo $favoritecity; // This will cause an error
$favoriteCity and $favoritecity are treated as two different variables because PHP is case-
sensitive.
1.7.2 Creating Variables –
In PHP, a variable is created when you assign a value to it using the assignment operator (=).
Numbers are written without quotes, while text (strings) must be enclosed in quotation marks. If
a variable already exists, assigning a new value will overwrite the previous value. You can also
assign the value of one variable to another.
✅ Examples of Creating Variables
$age = 21;
$price = 20.52;
$temperature = -5;
$name = "Ramesh";
Numbers are not enclosed in quotes.
Strings must be written inside quotes.
🔁 Changing Variable Values
$color = "blue";
$color = "red";
The first line creates $color and assigns "blue".
The second line changes its value to "red".
🔄 Assigning One Variable to Another
$name1 = "Suresh";
$name2 = "Patil";
$favorite_name = $name1;
Now, $favorite_name contains "Suresh".
➖ Creating an Empty Variable
$city = "";
This creates a variable without storing any actual value.
1.7.3 Displaying Variable Values – Explanation (3–5 Lines Theory)
You can display variable values using echo or print_r. The echo statement is commonly used to
print variables, strings, or multiple values together. If you try to use a variable that has not been
created, PHP will generate a warning message. Proper spelling of variable names is important to
avoid errors.
✅ Using print_r()
$today = "Sunday";
print_r($today);
Output:
Sunday
✅ Using echo
$age = 21;
echo $age;
Output:
21
✅ Using echo Inside HTML
$name = "Ramesh";
<p>Welcome <?php echo $name; ?></p>
Output on webpage:
Welcome Ramesh
⚠️Undefined Variable Error
echo $aeg;
Error Message:
Notice: Undefined variable: aeg
This occurs because $aeg was never created or assigned a value.
1.8 Working with Constants Constants are similar to variables. Constants are given names, and
values arestored in them. However, constants are constant; they can‘t be changed bythe script.
After you set the value for a constant, it stays the same. If you usea constant for weather and set
it to sunny, it can‘t be changed.
1.8.1 Creating Constants –
In PHP, constants are fixed values that cannot be changed once defined. They are created using
the define() function and do not begin with a dollar sign ($). By convention, constant names are
written in uppercase to distinguish them from variables. Constants can store strings or numeric
values and are accessible throughout the script.
✅ Syntax of Creating a Constant
define("CONSTANT_NAME", "value");
📌 Example 1: String Constant
define("WEATHER", "Sunny");
echo WEATHER;
Output:
Sunny
📌 Example 2: Numeric Constant
define("INTEREST", 0.01);
echo INTEREST;
Output:
0.01
⚠️Important Rules for Constants
Do not use $ before constant names.
Constant names are usually written in uppercase.
Avoid using PHP keywords as constant names.
For example, defining:
define("ECHO", "Hello");
echo ECHO;
may cause errors because echo is a PHP keyword.
🛑 Some Common PHP Keywords
Examples of reserved words in PHP include:
echo, print, if, else, while, for, function, class, return, switch, break, continue, include, require,
etc.
Using these as constant names can create confusion or errors.
Conclusion
Constants are used to store fixed values that remain unchanged throughout a script. Always use
descriptive uppercase names and avoid PHP keywords to prevent unexpected errors.
1.8.2 Understanding When to Use Constants –
In PHP, constants should be used when a value is fixed and should not change during the
execution of a script. They improve code clarity by using descriptive names instead of hard-
coded numbers. Constants also make maintenance easier because the value needs to be updated
in only one place. Most importantly, constants prevent accidental modification of important
values in large programs.
Why Use Constants?
✅ 1. Better Readability
Using a name like PRODUCT_COST is clearer than writing 20.50 throughout the script.
✅ 2. Easy Maintenance
If a value changes (like an exchange rate), you only update it once instead of editing multiple
lines.
✅ 3. Prevent Accidental Changes
Variables can be reassigned anywhere in the script, but constants cannot be modified once
defined.
🔴 Problem with Hard-Coded Values
<?php
$Indian_Rupee = 20.00;
$US_dollars = $Indian_Rupee * 0.014;
?>
If the exchange rate changes, you must update 0.014 everywhere it appears.
🟡 Using a Variable
<?php
$rate = 0.014;
$Indian_Rupee = 20.00;
$US_dollars = $Indian_Rupee * $rate;
?>
This allows updating the rate in one place.
However, $rate can still be changed accidentally later in the script.
🟢 Using a Constant
<?php
define("IR_TO_US", 0.014);
$Indian_Rupee = 20.00;
$US_dollars = $Indian_Rupee * IR_TO_US;
?>
The value cannot be changed later.
If you try IR_TO_US = 20;, PHP will generate an error.
Safer for large programs with thousands of lines of code.
✅ Final Rule
Use a constant when the value should remain unchanged.
Use a variable when the value needs to be modified during script execution.
1. Displaying Constants
A constant’s value can be displayed using:
o print_r(CONSTANT_NAME);
o echo CONSTANT_NAME;
Constants should not be enclosed in quotes while using echo.
o If written inside quotes ("IR_TO_US"), PHP will print the constant name instead
of its value.
Constants can also be used in complex output statements by separating items with
commas:
echo "The exchange rate is $", IR_TO_US;
Output:
The exchange rate is $0.014
Important Note:
o The dollar sign $ is placed inside the quoted string.
o The constant name is written separately without quotes.
2. Utilizing Built-in PHP Constants
PHP provides predefined (built-in) constants that give useful information about the script
environment.
Common Built-in Constants:
__LINE__ → Returns the current line number of the script.
__FILE__ → Returns the full path and filename of the current file.
Example:
echo __FILE__;
Output Example:
c:\program files\apache group\apache\htdocs\[Link]
Other Important Built-in Constants:
E_ALL → Reports all PHP errors.
E_ERROR → Reports fatal run-time errors.
These constants are mainly used for error handling and debugging.
Conclusion
Constants in PHP store fixed values and are accessed without quotes.
They can be displayed using echo or print_r().
PHP provides several built-in constants like __LINE__ and __FILE__ to retrieve script-
related information.
Error-level constants such as E_ALL help in managing error reporting.
1.9 Data Types in PHP
Data Types defines the type of data a variable can store. PHP allows eight different types of
data types. All of them are discussed below. The first five are called simple data types and the
last three are compound data types:
1.9.1 Integer: Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point. They can be
decimal (base 10), octal (base 8) or hexadecimal (base 16). The default base is
decimal (base 10). The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x. The range of integers must lie
between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1= 50;
$deci2= 654;
// octal base integers
$octal1= 07;
// hexadecimal base integers
$octal= 0x45;
$sum= $deci1+ $deci2;
echo$sum;
?>
Output:
704
1.9.2 Double: Can hold numbers containing fractional or decimal part including
positive and negative numbers. By default, the variables add a minimum number
of decimal places. Example:
<?php
$val1= 50.85;
$val2= 654.26;
$sum= $val1+ $val2;
echo$sum;
?>
Output:
705.11
1.9.3 String: Hold letters or any alphabets, even numbers are included. These are
written within double quotes during declaration. The strings can also be written
within single quotes but it will be treated differently while printing variables.
Example:
<?php
$name= "Krishna";
echo"The name of the Geek is $name \n";
echo'The name of the geek is $name';
?>
Output:
The name of the Geek is Krishna
The name of the geek is $name
1.9.4 NULL: These are special types of variables that can hold only one value i.e.,
NULL. We follow the convention of writing it in capital form, but its case
sensitive.
Example:
<?php
$nm= NULL;
echo$nm; // This will give no output
?>
1.9.5 Boolean: Hold only two values, either TRUE or FALSE. Successful events will
return true and unsuccessful events return false. NULL type values are also treated
as false in Boolean. Apart from NULL, 0 is also considering as false in boolean. If
a string is empty then it is also considered as false in boolean data type.
Example:
<?php
if(TRUE)
echo"This condition is TRUE";
if(FALSE)
echo"This condition is not TRUE";
?>
Output:
This condition is TRUE
1.9.6 Arrays: Array is a compound data-type which can store multiple values of same
data type. Below is an example of array of integers.
<?php
$intArray= array( 10, 20 , 30);
echo"First Element: $intArray[0]\n";
echo"Second Element: $intArray[1]\n";
echo"Third Element: $intArray[2]\n";
?>
Output:
First Element: 10
Second Element: 20
Third Element: 30
1.9.7 Objects: Objects are defined as instances of user defined classes that can hold
both values and functions. This is an advanced topic and will be discussed in
details in further articles.
1.9.8 Resources: Resources in PHP are not an exact data type. These are basically used
to store references to some function call or to external PHP resources. For
example, consider a database call. This is an external resource.
1.10 PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
1.10.3 PHP Comparison Operators The PHP comparison operators are used to compare two
values (number or string):
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
Operator Name Example Result
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
Returns true if $x is not equal to $y or they are not of the
!== Not identical $x !== $y
same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
Greater than or
>= $x >= $y Returns true if $x is greater than or equal to $y
equal
<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
1.10.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-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
1.10.5 PHP Logical Operators The PHP logical operators are used to combine conditional
statements.
Operator Name Example Result
And And $x and $y True if both $x and $y
are true
Or Or $x or $y True if either $x or $y
is true
Xor Xor $x xor $y True if either $x or $y
is true, but not both
&& And $x && $y True if both $x and $y
are true
Or
! Not !$x True if $x is not true
1.10.6 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
assignment $txt1
1.10.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
$x ==
== Equality Returns true if $x and $y have the same key/value pairs
$y
=== Identity $x === Returns true if $x and $y have the same key/value pairs in the same
$y order and of the same types
$x and
And And True if both $x and $y are true
$y
Or Or $x or $y True if either $x or $y is true
$x xor
Xor Xor True if either $x or $y is true, but not both
$y
$x &&
&& And True if both $x and $y are true
$y
Or
! Not !$x True if $x is not true
!= Inequality $x != $y Returns true if $x is not equal to $y
$x <>
<> Inequality Returns true if $x is not equal to $y
$y
$x !==
!== Nonidentity Returns true if $x is not identical to $y
$y
1.11 Using Conditional Statements
A conditional statement executes a block of statements only when certain conditions are true.
Conditional statements are widely used to control the flow of a program.
1.11.1 if Statement
The if statement sets up a condition and tests it. If the condition is true, a block of statements is
[Link] can add multiple elseif sections to test additional conditions. An optional else
section executes when none of the previous conditions are true.
General format:
if (condition) {
// block of statements
} elseif (condition) {
// block of statements
} else {
// block of statements
}
The if statement consists of three sections:
1. if (Required)
o Tests a condition.
o If the condition is true, the block of statements executes.
o If false, the script skips to any elseif or else sections.
2. elseif (Optional)
o Can have multiple elseif sections.
o Tests a condition; if true, executes the block of statements and skips the remaining
elseif/else sections.
o If false, moves to the next elseif or else.
3. else (Optional)
o Only one else section is allowed.
o Executes its block if all preceding if and elseif conditions are false.
Example: Assigning Grades Based on Score
if ($score > 92) {
$grade = "A";
$message = "Excellent!";
} elseif ($score <= 92 and $score > 83) {
$grade = "B";
$message = "Good!";
} elseif ($score <= 83 and $score > 74) {
$grade = "C";
$message = "Okay";
} elseif ($score <= 74 and $score > 62) {
$grade = "D";
$message = "Uh oh!";
} else {
$grade = "F";
$message = "Doom is upon you!";
}
echo $message . "\n";
echo "Your grade is $grade\n";
Explanation of flow:
1. $score is compared to 92.
o If greater than 92, $grade = A and $message = Excellent!. Script skips remaining
checks.
o If not, moves to the first elseif.
2. $score compared to 92 and 83.
o If in this range, $grade = B and $message = Good!. Script skips remaining checks.
3. $score compared to 83 and 74.
o If in this range, $grade = C and $message = Okay. Script skips remaining checks.
4. $score compared to 74 and 62.
o If in this range, $grade = D and $message = Uh oh!. Script skips remaining
checks.
5. If none of the above conditions are true:
o $grade = F and $message = Doom is upon you!.
Shortcut for Single Statements
If a block contains only one statement, curly braces {} can be omitted:
if ($grade > 92)
$grade = "A";
Useful for short statements, but can become confusing with nested or multiple if
statements.
Nesting if Statements
You can place one if statement inside another. They allow more complex decisions. For
example, you can check a customer’s state first, then check if they have an email address, and
decide whether to contact them by email or letter.
This is called nesting.
Example: Contacting Customers in Idaho
if ($custState == "ID") {
if ($EmailAdd == "") {
$contactMethod = "letter";
} else {
$contactMethod = "email";
}
} else {
$contactMethod = "none needed";
}
Explanation:
First, checks if the customer lives in Idaho.
If yes, checks for an email address:
o Blank → letter
o Not blank → email
If not in Idaho → none needed.
1.11.2 Switch statement: The switch statement is used to test one variable against
multiple values and execute different blocks of code depending on the match. It’s ideal
when you have several alternatives, like handling different state sales tax rates.
Syntax:
switch ($variablename) {
case value1:
// statements
break;
case value2:
// statements
break;
...
default:
// statements (optional)
break;
}
How it works:
1. Evaluates $variablename.
2. Executes the block of the first matching case.
3. Stops executing that case when it hits break or the end of the switch.
4. If no case matches, executes the default block (optional).
Important notes:
o break statements prevent “fall-through” to subsequent cases.
o The default case can be placed anywhere but is usually at the end.
o The last case does not strictly need a break, but including it improves clarity.
Example – Sales Tax Calculation:
switch ($custState) {
case "OR":
$salestaxrate = 0;
break;
case "CA":
$salestaxrate = 1.0;
break;
default:
$salestaxrate = 0.5;
break;
}
$salestax = $orderTotalCost * $salestaxrate;
Explanation:
o Oregon (OR) → tax = 0
o California (CA) → tax = 100%
o All other states → tax = 50% (handled by default)
1.11.3 Repeating Actions by Using Loops
Loops are used to repeat a block of statements either a set number of times or until a condition is
met. Loops are used frequently in scripts to set up a block of statements that repeat. The loop can
repeat a specified number of times. For example, a loop that echoes all the state capitals needs to
repeat 50 times. Or the loop can repeat until a certain condition is met.
1. A for loop: Sets up a counter; repeats a block of statements until the counter reaches a
specified number. The most basic for loops are based on a counter.
General Syntax:
for (startingvalue; endingcondition; increment) {
// block of statements
}
Components:
1. startingvalue: Initializes the counter variable.
o Example: $i = 1; sets $i to 1.
o Can start at 0, 1, or any number/expression/variable.
2. endingcondition: The loop continues while this condition is true.
o Example: $i <= 3; repeats until $i exceeds 3.
o Can involve variables like $i < $size;.
3. increment: Updates the counter each iteration.
o Example: $i++; adds 1 per loop.
o Can also use $i += 1; or $i--;.
Example – Print “Hello World” three times:
for ($i = 1; $i <= 3; $i++) {
echo "$i. Hello World!<br>";
}
Notes:
Indentation is optional, but it improves readability.
Counter variables like $i can be used inside the loop.
Nested Loops Example – Multiplication Tables 1–9:
for ($i = 1; $i <= 9; $i++) {
echo "\nMultiply by $i\n";
for ($j = 1; $j <= 9; $j++) {
$result = $i * $j;
echo "$i x $j = $result\n";
}
}
Output:
Multiply by 1
1x1=1
1x2=2
...
1x9=9
Multiply by 2
2x1=2
2x2=4
...
2 x 9 = 18
...
You can nest for loops to perform repeated actions within repeated actions.
1.11.4 A while loop: repeats a block of code as long as a specified condition is true. The
condition is checked before each iteration, and if it becomes false, the loop stops. This type of
loop is useful when you don’t know in advance how many times you need to repeat an action,
like searching through an array or reading files. Care must be taken to avoid infinite loops, where
the condition never becomes false.
Example – Searching an array for “apple”:
$fruit = array("orange", "apple", "grape");
$k = 0;
$found = false;
while (!$found) {
if ($fruit[$k] == "apple") {
echo "apple\n";
$found = true;
} else {
echo "$fruit[$k] is not an apple\n";
}
$k++;
}
Output:
orange is not an apple
apple
This loop checks each element of the array until it finds “apple” and stops.
1.11.5 A do..while loop: A do..while loop executes a block of statements at least once and then
checks a condition at the bottom of the loop. If the condition is true, it repeats; if false, it stops.
Unlike a while loop, which tests the condition before the first iteration, a do..while guarantees
the code runs at least one time. This is useful when you want the loop to run once regardless of
the condition, such as prompting a user or checking array elements.
Example – Searching an array for “apple”:
$fruit = array("orange", "apple", "grape");
$k = 0;
$found = false;
do {
if ($fruit[$k] == "apple") {
echo "apple\n";
$found = true;
} else {
echo "$fruit[$k] is not an apple\n";
}
$k++;
} while (!$found);
Output:
orange is not an apple
apple
Key Difference from while loop: Even if the condition is initially false, the do..while
loop executes the statements once, while a while loop would not run at all.
1.12 Comments in PHP
Comments in PHP are ignored by the PHP engine and are used to make code more readable and
understandable. They help explain the purpose of code for other developers or for
documentation. PHP supports single-line comments using // or #, and multi-line comments
using /* ... */. Single-line comments are for short explanations, while multi-line comments can
span multiple lines.
Examples:
// Single-line comment
# Another single-line comment
echo "Hello World!";
/* Multi-line comment
Explains variables and code logic */
$geek = "Hello World!";
echo $geek;
Output:
Hello World!
Hello World!
Key point: Comments do not affect program execution; they are purely for readability.
1.13 Pre-defined Functions in PHP (Built in Functions):
1. PHP String Functions
PHP provides many built-in functions to manipulate strings. You can extract substrings, replace
text, count characters or words, split strings into arrays, and remove extra spaces. Commonly,
trim(), ltrim(), and rtrim() are used to remove spaces from strings. Case conversion functions like
strtolower(), strtoupper(), ucfirst(), and lcfirst() help format text. Hashing functions like md5()
and sha1() generate secure string hashes.
Descripti
Function Example Output
on
Removes
leading &
trim($str) trim(" Hello ") Hello
trailing
spaces
Removes
ltrim($str) leading ltrim(" Hello ") Hello
spaces
Removes
rtrim($str) trailing rtrim(" Hello ") Hello
spaces
Converts
strtolower($str) string to strtolower("Benjamin") benjamin
lowercase
Converts
strtoupper("george w
strtoupper($str) string to GEORGE W BUSH
bush")
uppercase
Counts all
characters strlen("united states of
strlen($str) 24
including america")
spaces
Converts
explode(delim,$str) string into explode(";","a;b;c") [a,b,c]
an array
Extracts
substr("This is
substr($str,start,len) part of a This
long",0,4)
string
Replaces
str_replace(old,new, str_replace("the","that",
text in a that laptop
$str) "the laptop")
string
Returns
position of strpos("PHP
strpos($str,word) 4
a Programming","Pro")
substring
Returns
md5($str) MD5 hash md5("password") 5f4dcc3b5aa765d61d8327deb882cf99
of string
sha1($str) Returns sha1("password") 5baa61e4c9b93f3f0682250b6cf8331b7e
Descripti
Function Example Output
on
SHA-1
hash of e68fd8
string
Counts
words or
str_word_count("Hello
str_word_count($str) returns 2
world")
words
array
Capitalize
ucfirst($str) s first ucfirst("respect") Respect
character
Makes
first
lcfirst($str) lcfirst("RESPECT") rESPECT
character
lowercase
2. PHP Numeric Functions
Numeric functions in PHP are used to validate numbers, format values, perform calculations, or
generate random numbers. is_numeric() checks if a value is numeric. number_format() formats
numbers with commas or decimals. rand() generates random numbers, while round(), sqrt(), and
trigonometric functions like sin(), cos(), tan() help in mathematical computations. pi() returns the
constant π for calculations.
Function Description Example Output
Checks if the value is
is_numeric($val) is_numeric("guru") false
numeric
Checks if the value is
is_numeric($val) is_numeric(123) true
numeric
Formats numbers with
number_format($num) number_format(2509663) 2,509,663
commas
rand() Generates a random number rand() Random
Rounds number to nearest
round($num) round(3.49) 3
integer
Returns square root of
sqrt($num) sqrt(100) 10
number
Returns sine of angle (in
sin($angle) sin(45) 0.8509
radians)
cos($angle) Returns cosine of angle cos(45) 0.5253
tan($angle) Returns tangent of angle tan(45) 1.6198
Function Description Example Output
pi() Returns value of PI constant pi() 3.1415926535898
1.13.2 PHP Dates and Times
PHP handles dates and times using UNIX timestamps, which count seconds since January 1,
1970, 00:00:00 GMT. This makes it easy to calculate differences between two dates by
subtraction. The date() function converts a timestamp into a human-readable format, while time()
and strtotime() provide the current timestamp or parse date strings. You can also store specific
dates with mktime() or strtotime() using readable English-like keywords such as "tomorrow",
"last Saturday", or "next year". PHP provides many format symbols to display dates and times in
various styles.
Common Date/Time Functions
Function Description Example Output
Returns current
time() $today = time(); 1677435610
timestamp
Converts readable string $d = strtotime("January 15
strtotime(str) 1042636800
to timestamp 2003");
Creates timestamp for $d =
mktime(h,m,s,mo,d,y) 1042636800
specific date/time mktime(0,0,0,1,15,2003);
Formats timestamp into
date(format,$timestamp) date("Y/m/d") 2026/02/26
readable date
Finds difference in seconds
$today - $pastDate $diff = $today - $pastDate;
seconds elapsed
($today - Converts difference to $hours = ($today-
hours elapsed
$pastDate)/3600 hours $pastDate)/3600;
Common Date Format Symbols
Symbol Meaning Example
Y Year in 4 digits 2026
y Year in 2 digits 26
m Month with leading zero 02
n Month without leading zero 2
d Day with leading zero 09
j Day without leading zero 9
H Hour 0–23 14
G Hour 0–12 2
i Minutes 05
s Seconds 30
A AM/PM uppercase PM
M Month text abbreviated Jan
F Month text full January
Date Arithmetic Examples
$today = time();
$importantDate = strtotime("last Saturday");
$timeSpan = $today - $importantDate; // seconds elapsed
$hours = $timeSpan / 3600; // hours elapsed
$future = strtotime("tomorrow 4am"); // timestamp for tomorrow 4 AM
PHP allows flexible date expressions using English words like tomorrow, now + 24
hours, 2 weeks ago, next year gmt.
Subtracting timestamps gives differences in seconds; dividing by 60 or 3600 converts it
to minutes or hours.
Questions
1 Define PHP. What these tags specify in PHP <?php and ?> 5
2 Can we run PHP from HTML file? If yes, how? 5
3 Why PHP is known as scripting language? 5
4 Write a program in PHP to calculate Square Root of a number. 5
5 List different data types and explain with example. 5
6 Explain comments in PHP 5
7 List different operators and explain with example. 5
8 Write the name of PHP functions that can be used to build a function that accepts any number
of arguments 5
9 Explain in details predefined functions 5
10 Explain various date and time formats. 5
11 Write a PHP script to compute factorial of n using while or for loop 5
12 Write a PHP script to display Fibonacci of length 10 5
13 Write a short note on Scope of Variables 5
14 List different loops used in PHP in details 5
15 List different decision making used in PHP in details 5
16 What is the function of for-each construct in PHP? 5
17 Explain various Math function available in PHP. 5
18 Differentiate While and Do-While statement 5