You are on page 1of 85

PHP and MySQL

BCA – VI Semester NEP

By:

Satish Naik

Published by

Kamadhenu BCA College Karwar


Affiliated to Karnatak University Dharwad, Redg by Govt of Karnataka

Kamadhenu BCA College -1-


BCA Semester–VI
Discipline Specific Course (DSCC-15)
Course Title: PHP and MySQL
Course Code:056BCA012
Type ofTheory Instruction Total No.of Duration Formative Summative Total
Course/Practical Credits hour per week Lectures/Hours of Exam Assessment assessment Marks
/Semester Marks Marks
DSCC-15 Theory 04 04 56hrs. 2hrs. 40 60 100

Course Outcomes (COs): At the end of the course students will be able to:CO1: Design dynamic and
interactive web pages and websites. CO2: Run PHP scripts on the server and retrieve results.
CO3: Handle databases like MySQL using PHP in websites.
Unit Contents Page Nos
Introduction to PHP: Introduction to PHP, History and Features of PHP, Installation &
Configuration of PHP, Embedding PHP code in Your Web Pages, Understanding PHP,
Unit I HTML and White Space, Writing Comments in PHP, Sending Data to the Web Browser,
Data types in PHP, Keywords in PHP, Using Variables, Constants in PHP, Expressions
in PHP, Operators in PHP.
Programming with PHP: Conditional statements: if, if-else, switch, The? Operator,
Unit II Looping statements: while Loop, do-while Loop, for Loop
Arrays in PHP: Introduction- What is Array? Creating Arrays, Accessing Array
elements, Types of Arrays: Indexed v/s Associative arrays, Multidimensional arrays,
Creating Array, Accessing Array, Manipulating Arrays, displaying array, Using Array
Functions, Including and Requiring Files- use of Include () and Require (), Implicit and
Explicit Casting in PHP.
Using Functions, Class- Objects, Forms in PHP: Functions in PHP, Function
definition, Creating and invoking user-defined functions, Formal parameters versus
Unit III actual parameters, Function and variable scope, Recursion, Library functions, Date
and Time Functions Strings in PHP: What is String? , Creating and Declaring String,
String Functions
Class &Objects in PHP: What is Class & Object, Creating and accessing a Class
&Object, Object properties, object methods, Overloading, inheritance, Constructor and
Destructor
Form Handling: Creating HTML Form, Handling HTML Form data in PHP
Database Handling Using PHP with MySQL: Introduction to MySQL: Database
terms, Data Types.
Accessing MySQL –Using MySQL Client and Using PHP MyAdmin, MySQL
Unit IV Commands, Using PHP with MySQL: PHP MySQL Functions, connecting to MySQL
and Selecting the Database, Executing Simple Queries, Retrieving Query Results,
Counting Returned Records, Updating Records with PHP
References:
1. PHP & MySQL for Dynamic Web Sites-Fourth Edition By Larry Ullman.
2. Learning PHP, MySQL and JavaScript By Robin Nixon–O‟REILLY Publications
3. Programming PHP By RasmusLerdorf, Kevin Tatroe, Peter Macintyre
4. SAMS Teach Yourself PHP in 24 hours, Author: Matt Zandstra, Sams Publishing

Kamadhenu BCA College -2-


Unit – 1: Introduction to PHP

PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is
the latest version of PHP, which was released on 28 November. Some important points need to
be noticed about PHP are as followed:
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web applications with
MySQL database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.

Kamadhenu BCA College -3-


o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration form.

PHP Features
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below:

Performance:
PHP script is executed much faster than those scripts which are written in other languages such as
JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically
reduced, which results in faster processing speed and better performance.

Kamadhenu BCA College -4-


Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of
PHP according to your requirement without paying any cost. All its components are free to
download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent
threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work
in a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.

Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic websites easily. But
you must have the basic the knowledge of following technologies for web development as well.
o HTML
o CSS
o JavaScript
Kamadhenu BCA College -5-
o Ajax
o XML and JSON
o jQuery

Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript.
So, learn these technologies for better implementation of PHP.

HTML - HTML is used to design static webpage.

CSS - CSS helps to make the webpage content more effective and attractive.

JavaScript - JavaScript is used to design an interactive website.

History of PHP
As it is realized today, PHP is truly the standby to an item named PHP/FI. It was introduced in 1994
by Rasmus Lerdorf, the absolute first exhibition of PHP was a direct arrangement of Common
Gateway Interface (CGI) parallels inscribed in the C programming language. Initially utilized for
ensuring visits to his internet-based resume, he named the set-up contents " the Individual
Home Page Tools," all the more normally referred to as " the PHP Tools." With time,
furthermore, functionalities were wanted, and Lerdorf revised his PHP Tools, capable of delivering
a lot bigger and more extravagant execution. This model now was capable of information base
cooperation; this gives a structured framework through which clients could faster basic powerful
web applications. In June of 1995, Lerdorf delivered his source code for the PHP Tools developers'
population, allowing engineers and developers worldwide to use it to their best advantage. This
additionally allowed and urged clients to give bug fixes in the code and, for the best part, to refine
it.

In September 1995, Lerdorf redeveloped PHP, and he dropped the name PHP. Presently alluding
to the devices as FI (another way to say " Form Interpreter " ), the new execution incorporated
a portion of the fundamental usefulness of PHP as far as we might be concerned today. It had
variables that were somewhat similar to Perl, form variables can be automatically distinguished,
and HTML imbibed syntax. PHP resembles pearl in syntax but is considerably more limited, easy
to use, and unpredictable. Indeed, to imbibe the code into an HTML document, developers have
to utilize comments in HTML. However, this strategy was not completely welcomed. FI kept getting
popular as a CGI instrument but not exactly as a language.

The language was purposely intended to look alike C in structure, making it a simple reception for
developers acquainted with C, Perl, and commonly available languages. Notwithstanding, this
started to change the next month; in October 1995, Lerdorf delivered a total revise of the code.
Bringing back the original name PHP, it was momentarily named "Personal Home Page
Construction Kit," It was only released to boast that it was the most advanced scripting interface
present.

Kamadhenu BCA College -6-


In the midst of 1996, the previous code gets a total makeover. Using the names of previous
updates, Lerdorf reintroduced PHP - FI. The next-generation implementations genuinely advance
PHP from a set-up of instruments into a programming language on its own.

1. Creation (1994-1995): PHP was originally created by Danish-Canadian programmer


Rasmus Lerdorf in 1994. Initially, it was a set of Common Gateway Interface (CGI) binaries
written in the C programming language, used for tracking visits to his online resume.
2. Personal Home Page Tools (PHP Tools) (1995-1997): Lerdorf released the first version
of PHP Tools (Personal Home Page Tools) in 1995. These tools included a parser for form
data, a simple templating system, and the ability to communicate with databases. It was
intended for managing his personal homepage but quickly gained popularity among
developers for its ease of use.
3. PHP/FI (Forms Interpreter) (1997-1998): In 1997, two Israeli developers, Zeev Suraski
and Andi Gutmans, rewrote the parser for PHP, creating PHP/FI (Forms Interpreter). This
version introduced many features still found in PHP today, including support for forms,
databases, and dynamic web page creation.
4. PHP 3 (1998-2000): PHP 3 was a significant milestone, released in 1998. It was a complete
rewrite of PHP/FI and brought several improvements, including support for more web
servers, better performance, and a more stable codebase. PHP 3 gained significant traction,
becoming one of the most popular server-side scripting languages for web development.
5. PHP 4 (2000-2004): PHP 4, released in 2000, introduced numerous features and
improvements, such as support for object-oriented programming, better performance, and
more advanced database connectivity options. This version solidified PHP's position as a
leading web development language.
6. PHP 5 (2004-2014): PHP 5, released in 2004, was a major upgrade over PHP 4. It
introduced features like improved support for object-oriented programming, exceptions
handling, SQLite support, and performance enhancements. PHP 5 also laid the foundation
for modern PHP frameworks like Symfony, Laravel, and Zend Framework.
7. PHP 6 (Unreleased): PHP 6 was initially planned as the next major version of PHP,
intended to include full Unicode support and other enhancements. However, due to
various technical challenges and delays, including difficulties in implementing Unicode
support effectively, PHP 6 was ultimately abandoned.
8. PHP 7 (2015-Present): PHP 7, released in December 2015, is a significant update known
for its improved performance and reduced memory consumption. It introduced the Zend
Engine 3.0, which dramatically boosted performance, along with many new language
features and improvements. PHP 7 marked a new era for PHP, making it faster, more
secure, and more efficient for web development.
9. PHP 8 (2020-Present): PHP 8, released in November 2020, brought several new features,
performance improvements, and syntactic enhancements. Notable additions include the
Just-In-Time (JIT) compiler, union types, named arguments, attributes, and improvements
to the type system and error handling.

Throughout its history, PHP has evolved from a simple set of tools for managing personal
homepages to a powerful, versatile language used by millions of developers worldwide for
building dynamic web applications, content management systems, e-commerce platforms, and
more. It continues to evolve with regular updates and contributions from a large and active
community.

Kamadhenu BCA College -7-


Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that are
given below:

o WAMP for Windows


o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for WAMP.
In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

How to install XAMPP server on windows


We will learn how to install the XAMPP server on windows platform step by step. Follow the below
steps and install the XAMPP server on your system.

Step 1: Click on the above link provided to download the XAMPP server according to your
window requirement.

Kamadhenu BCA College -8-


Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to make
changes in your system. A window will pop-up, where you have to click on the Next button.

Step 3: Here, select the components, which you want to install and click Next.

Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.

Kamadhenu BCA College -9-


Step 5: Click Next and move ahead.

Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.

Kamadhenu BCA College -10-


Step 7: A finish window will display after successful installation. Click on the Finish button.

Step 8: Choose your preferred language.

Kamadhenu BCA College -11-


Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on
the localhost.

How to run PHP programs on XAMPP, see in the next tutorial.

Step 10: If no error is shown, then XAMPP is running successfully.

Kamadhenu BCA College -12-


Embedding PHP code in Your Web Pages:
If we want to use PHP in the Html document, then we have to follow the steps which are given
below. Using these simple steps, we can easily add the PHP code.

Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in
the text editor in which we want to use the PHP.
1. <!Doctype Html>
2. <Html>
3. <Head>
4. <Title>
5. Use a Php in Html
6. </Title>
7. </Head>
8. <Body>
9. </Body>
10. </Html>

Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the
code of PHP. And, then we have to type the start and end tag of PHP.

1. <h1>
2. <?php ?>
3. </h1>

Step 3: After then, we have to type the code of PHP between the tags of PHP.

1. <h1>
2. <?php
3. echo "Hii User!! You are at JavaTpoint Site"
4. ?>
5. </h1>

Step 4: When we successfully add the PHP code, then we have to save the Html file and then run
the file in the browser.

1. <!Doctype Html>
2. <Html>
3. <Head>
4. <Title>
5. Use a Php in Html
6. </Title>
7. </Head>

Kamadhenu BCA College -13-


8. <Body>
9. <h1><?php echo "Hii User!! You are at JavaTpoint Site" ?></h1>
10. </Body>
11. </Html>

Example #1
Code:

<html>
<title>First Application of PHP</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
echo "Welcome User";
?>
</body>
</html>

White Space
White Space is a property defined in CSS (Cascading Style Sheets) that enable the user to
control the text wrapping and white spaces inside an element of the website. It can take
several types of values depending upon the user's need.

Syntax of White Space Property


The syntax of implementing the white-space property in CSS is similar to any other
property that is property_name: value;
white-space: value;
Several values that can be passed to the white-space property are:
1. white-space: normal;
2. white-space: nowrap;
3. white-space: pre;
4. white-space: pre-wrap;
5. white-space: pre-line;
6. white space: break-spaces;

Functions Performed by Different values in white-space


o normal: This value collapses a sequence of white spaces. The new line character is also
considered white space. If the lines are broken, then the line must fill the line boxes.

Kamadhenu BCA College -14-


o nowrap: Using this value, it treats white space between the element as normal, but it
suppresses the line breaks or the text wrapping in the source.
o pre: It does not collapse the white spaces they are preserved. The lines are only
discontinued by the new line characters and break tags mentioned in the website's source.
o pre-wrap: The sequences of white space are preserved. It is similar to pre as the sequence
of white-space are preserved. The lines are either broken on the new line or due to the
break tag in the source code. The only difference is that it requires filling the line boxes
too.
o pre-line: The value collapses the white spaces in the content. The lines are broken due to
the new line characters or the break tag. It is necessary to fill the line boxes.

Implementing white-space property

Normal: It is the default value for the property. It will perform text wrapping whenever necessary.
When the normal value is assigned to the white-space property, every sequence with more than
two spaces will be replaced by a single white space.

Syntax
1. white-space: normal;

Below is an example to illustrate the implementation of white-space property using normal as the
value.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> CSS | white-space Property using normal value</title>
5. <style>
6. div {
7. width: 500px;
8. height: 500px;
9. white-space: normal;
10. background-color: rgb(23, 102, 23);
11. color: white;
12. font-size: 30px;
13. }
14. </style>
15. </head>
16.
17. <body>
18. <center>
Kamadhenu BCA College -15-
19. <div> Using white-space property
20. <br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptas, illum.
21. </div>
22. </center>
23. </body>
24. </html>

Nowrap: When the white space property is assigned a nowrap value. Every sequence of
characters with more than two spaces will be represented as a single space. It won't
perform wrapping unless the user specifies it.

Syntax

1. white-space: nowrap;

Below is an example to illustrate the implementation of white-space property using


nowrap as the value.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> CSS | white-space Property using nowrap value</title>
5. <style>
6. div {
7. width: 500px;
8. height: 500px;
9. white-space: nowrap;
10. background-color: rgb(23, 102, 23);
11. color: rgb(133, 28, 28);
12. font-size: 30px;
13. }
14. </style>
Kamadhenu BCA College -16-
15. </head>
16.
17. <body>
18. <center>
19. <div> Using white-space property
20. <br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptas, illum.
21. </div>
22. </center>
23. </body>
24. </html>

Output:

PHP Comments
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. PHP supports single line
and multi-line comments. These comments are similar to C/C++ and Perl style (Unix shell
style) comments.

PHP Single Line Comments


There are two ways to use single line comments in PHP.
o // (C++ style single line comment)
o # (Unix Shell style single line comment)
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>
Output:
Welcome to PHP single line comments
Kamadhenu BCA College -17-
PHP Multi Line Comments
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within
/* */. Let's see a simple example of PHP multiple line comment.
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>

Output:
Welcome to PHP multi line comment

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET
and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use $_GET,
for post request $_POST.

1. GET method
2. POST method

PHP Get Form


Get request is the default form request. The data passed through get request is visible on the URL
browser so it is not secured. You can send limited amount of data through get request.

Let's see a simple example to receive data from get request in PHP.

File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
Kamadhenu BCA College -18-
PHP Post Form
Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc. The data passed through post
request is not visible on the URL browser so it is secured. You can send large amount of
data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variab
le
echo "Welcome: $name, your password is: $password";
?>

Output:

Kamadhenu BCA College -19-


PHP Data Types
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types

PHP Data Types: Scalar Types


It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.
1. resource
2. NULL

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE
(0). It is often used with conditional statements. If the condition is correct, it returns TRUE
otherwise FALSE.

Example:

<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>

Output:
This condition is TRUE.

PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.

Kamadhenu BCA College -20-


Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e.,
-2^31 to 2^31.

Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>

Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.

Example:

<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812

PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.

String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:

Kamadhenu BCA College -21-


Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>

Output:

Hello Javatpoint
Hello $company

PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.

Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>

Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

You will learn more about array in later chapters of this tutorial.

PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.

Kamadhenu BCA College -22-


Example:

<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

Output:

Bike Model: Royal Enfield

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls
or references to external PHP resources. For example - a database call. It is an external resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

PHP Keywords

PHP has a set of keywords that are reserved words which cannot be used as function names, class
names or method names. Prior to PHP 7, these keywords could not be used as class property
names either:

Keyword Description
abstract Declare a class as abstract
and A logical operator
as Used in the foreach loop
break Break out of loops and switch statements
Kamadhenu BCA College -23-
callable A data type which can be executed as a function
case Used in the switch conditional
catch Used in the try..catch statement
class Declare a class
clone Create a copy of an object
const Define a class constant
continue Jump to the next iteration of a loop
declare Set directives for a block of code
default Used in the switch statement
do Create a do...while loop
echo Output text
else Used in conditional statements
elseif Used in conditional statements
empty Check if an expression is empty
enddeclare End a declare block
endfor End a for block
endforeach End a foreach block
endif End an if or elseif block
endswitch End a switch block
endwhile End a while block
extends Extends a class or interface
final Declare a class, property or method as final
finally Used in the try...catch statement
fn Declare an arrow function
for Create a for loop
foreach Create a foreach loop
function Create a function
global Import variables from the global scope
goto Jump to a line of code
if Create a conditional statement
implements Implement an interface
include Embed code from another file
include_once Embed code from another file
instanceof Test an object's class
insteadof Resolve conflicts with traits
interface Declare an interface
isset Check if a variable exists and is not null
list Assigns array elements into variables
namespace Declares a namespace
new Creates an object
or A logical operator
print Output text
private Declare a property, method or constant as private
protected Declare a property, method or constant as
protected
public Declare a property, method or constant as public
require Embed code from another file
require_once Embed code from another file
return Exit a function and return a value
static Declare a property or method as static
Kamadhenu BCA College -24-
switch Create a switch block
throw Throw an exception
trait Declare a trait
try Create a try...catch structure
unset Delete a variable or array element
use Use a namespace
var Declare a variable
while Create a while loop or end a do...while loop
xor A logical operator
yield Used in generator functions
yield from Used in generator functions

PHP Variables
Variables are "containers" for storing information.

Creating (Declaring) PHP Variables


In PHP, a variable starts with the $ sign, followed by the name of the variable:
$x = 5;
$y = "John"

In the example above, the variable $x will hold the value 5, and the
variable $y will hold the value "John".

PHP Variables

A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).

Rules for PHP variables:


• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _)
• Variable names are case-sensitive ($age and $AGE are two different
variables)

Remember that PHP variable names are case-sensitive!

Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
$txt = "W3Schools.com";
echo "I love $txt!";

Kamadhenu BCA College -25-


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

$txt = "W3Schools.com";
echo "I love " . $txt . "!";
The following example will output the sum of two variables:

$x = 5;
$y = 4;
echo $x + $y;

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type the
variable is.

PHP automatically associates a data type to the variable, depending on its value.
Since the data types are not set in a strict sense, you can do things like adding a
string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data type
expected when declaring a function, and by enabling the strict requirement, it will
throw a "Fatal Error" on a type mismatch.

Variable Types
PHP has no command for declaring a variable, and the data type depends on the
value of the variable.
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:

Kamadhenu BCA College -26-


$x = "John"; echo $x;

Assign Multiple Values

You can assign the same value to multiple variables in one line:

$x = $y = $z = "Fruit";

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be
referenced/used.

PHP has three different variable scopes:


• local
• global
• static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
Example
Variable with global scope:

$x = 5; // global scope

function myTest() {

// using x inside this function will generate an error

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

myTest();

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

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

Example

Variable with local scope:

function myTest() {

$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";

}
Kamadhenu BCA College -27-
myTest();

// using x outside the function will generate an error


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

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

$x = 5;

$y = 10;

function myTest() {

global $x, $y;

$y = $x + $y;

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
$x = 5;

$y = 10;

function myTest() {

$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];

myTest();

echo $y; // outputs 15

Kamadhenu BCA College -28-


PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for
a further job.

To do this, use the static keyword when you first declare the variable:

function myTest() {

static $x = 0;

echo $x;

$x++;

myTest();
myTest();
myTest();

PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the
script except for magic constants, which are not really constants. PHP constants can be
defined by 2 ways:
1. Using define() function
2. Using const keyword
Constants are similar to the variable except once they defined, they can never be
undefined or changed. They remain constant across the entire program. PHP constants
follow the same PHP variable rules. For example, it can be started with a letter or
underscore only.
Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()


Use the define() function to create a constant. It defines constant at run time. Let's see the
syntax of define() function in PHP.
1. define(name, value, case-insensitive)
1. name: It specifies the constant name.
2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is
false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

Kamadhenu BCA College -29-


File: constant1.php
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>

Output:

Hello JavaTpoint PHP

Create a constant with case-insensitive name:

File: constant2.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
echo MESSAGE, "</br>";
echo message;
?>

Output:
Hello JavaTpoint PHP
Hello JavaTpoint PHP

File: constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

PHP constant: const keyword


PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const keyword
are case-sensitive.

File: constant4.php
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>

Kamadhenu BCA College -30-


Output:

Hello const by JavaTpoint PHP

Constant() function
There is another way to print the value of constants using constant() function instead of using the
echo statement.
Syntax

The syntax for the following constant function:


1. constant (name)
File: constant5.php
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Output:
JavaTpoint
JavaTpoint

Constant vs Variables
Constant Variables
Once the constant is defined, it can never be A variable can be undefined as well as

redefined. redefined easily.

A constant can only be defined using define() A variable can be defined by simple
function. It cannot be defined by any simple assignment (=) operator.
assignment.

There is no need to use the dollar ($) sign To declare a variable, always use the dollar ($)
before constant during the assignment. sign before the variable.

Constants do not follow any variable scoping Variables can be declared anywhere in the
rules, and they can be defined and accessed program, but they follow variable scoping

anywhere. rules.

Constants are the variables whose values can't The value of the variable can be changed.
be changed throughout the program.

By default, constants are global. Variables can be local, global, or static.

Kamadhenu BCA College -31-


PHP Expressions

Introduction
Anything that has a value is an expression. In a typical assignment statement
($x=100), a literal value, a function or operands processed by operators is an
expression, anything that appears to the right of assignment operator (=)

Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression

What is a Regular Expression?


A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe
what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text
replace operations.

Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and
optional modifiers.

$exp = "/w3schools/i";

In the example above, / is the delimiter, w3schools is the pattern that is being
searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or
space. The most common delimiter is the forward slash (/), but when your pattern
contains forward slashes it is convenient to choose other delimiters such as # or
~.

Regular Expression Functions


PHP provides a variety of functions that allow you to use regular expressions.
The most common functions are:
Function Description
preg_match() Returns 1 if the pattern was found in the string
and 0 if not
preg_match_all() Returns the number of times the pattern was
found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns
have been replaced with another string

Kamadhenu BCA College -32-


Using preg_match()
The preg_match() function will tell you whether a string contains matches of a
pattern.
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a
string:

$str = "Visit W3Schools";

$pattern = "/w3schools/i";

echo preg_match($pattern, $str);

Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a
pattern in a string.

Example
Use a regular expression to do a case-insensitive count of the number of
occurrences of "ain" in a string:

$str = "The rain in SPAIN falls mainly on the plains.";

$pattern = "/ain/i";

echo preg_match_all($pattern, $str);

PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values. For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
PHP Operators can be categorized in following forms:
Category Operator Description
Arithmetic + Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
** Exponentiation
Assignment = Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
Kamadhenu BCA College -33-
Comparison == Equal
=== Identical
!= or <> Not equal
!== Not identical
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical && or and Logical AND
`
xor Exclusive OR
! Logical NOT
Bitwise & Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
<< Shift left
>> Shift right
String . Concatenation
Increment/Decrement ++ Increment
-- Decrement
Ternary ? : Conditional (Ternary)
Null Coalescing ?? Null Coalescing (PHP 7)
Spaceship <=> Spaceship (PHP 7)
We can also categorize operators on behalf of operands. They can be categorized in 3
forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

PHP Operators Precedence


Let's see the precedence of PHP operators with associativity.
Operators Additional Information Associativity
clone new clone and new non-associative
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) increment/decrement and right
(array) (object) (bool) @ types
instanceof types non-associative
! logical (negation) right
*/% arithmetic left
+-. arithmetic and string left
concatenation
<< >> bitwise (shift) left
< <= > >= comparison non-associative
== != === !== <> comparison non-associative

Kamadhenu BCA College -34-


& bitwise AND left
^ bitwise XOR left
| bitwise OR left
&& logical AND left
|| logical OR left
?: ternary left
= += -= *= **= /= .= %= assignment right
&= |= ^= <<= >>= =>
and logical left
xor logical left
or logical left
, many uses (comma) left

Kamadhenu BCA College -35-


Unit II : Programming with PHP
Conditional Statements
In PHP, conditional statements are used to execute different blocks of code based on specified
conditions. The most common conditional statements in PHP are if, else if (or elseif), and else.
Additionally, PHP also supports the switch statement for multi-way branching based on the value
of an expression. Here's a brief overview of each:

PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement
in PHP.
o if
o if-else
o if-else-if
o nested if

PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true. If
statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax

if(condition){
//code to be executed
}

Flowchart

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

Output:
12 is less than 100

Kamadhenu BCA College -36-


PHP If-else Statement

PHP if-else statement is executed whether condition is true or false. If-else statement is
slightly different from if statement. It executes one block of code if the specified
condition is true and another block of code if the condition is false.

Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}

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

Output:

12 is even number

PHP If-else-if Statement


The PHP if-else-if is a special statement used to combine multiple if?.else statements. So,
we can check multiple conditions using this statement.
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}

Kamadhenu BCA College -37-


Example
<?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

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
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}

Kamadhenu BCA College -38-


Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>

Output:

Eligible to give vote

PHP Switch Example

<?php
$a = 34; $b = 56; $c = 45;
if ($a < $b) {
if ($a < $c) {
echo "$a is smaller than $b and $c";
}
}
?>

Output:

34 is smaller than 56 and 45

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works
like PHP if-else-if statement.

Kamadhenu BCA College -39-


Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must always be
the last statement.
2. There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example


<?php case 30:

$num=20; echo("number is equal to 30");


switch($num){ break;

case 10: default:


echo("number is equals to 10"); echo("number is not equal to 10, 20 or

break; 30");

case 20: }
echo("number is equal to 20"); ?>

break;

Output:
number is equal to 20

Kamadhenu BCA College -40-


PHP nested switch statement
Nested switch statement means switch statement inside another switch statement. Sometimes it
leads to confusion.

1. <?php
2. $car = "Hyundai";
3. $model = "Tucson";
4. switch( $car )
5. {
6. case "Honda":
7. switch( $model )

Kamadhenu BCA College -41-


8. {
9. case "Amaze":
10. echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
11. break;
12. case "City":
13. echo "Honda City price is 9.91 - 14.31 Lakh.";
14. break;
15. }
16. break;
17. case "Renault":
18. switch( $model )
19. {
20. case "Duster":
21. echo "Renault Duster price is 9.15 - 14.83 L.";
22. break;
23. case "Kwid":
24. echo "Renault Kwid price is 3.15 - 5.44 L.";
25. break;
26. }
27. break;
28. case "Hyundai":
29. switch( $model )
30. {
31. case "Creta":
32. echo "Hyundai Creta price is 11.42 - 18.73 L.";
33. break;
34. case "Tucson":
35. echo "Hyundai Tucson price is 22.39 - 32.07 L.";
36. break;
37. case "Xcent":
38. echo "Hyundai Xcent price is 6.5 - 10.05 L.";
39. break;
40. }
41. break;
42. }
43. ?>

Output:

Kamadhenu BCA College -42-


Hyundai Tucson price is 22.39 - 32.07 L.

Practice programs:

Program to check if a number is even or odd:


<?php
$number = 7;

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

2. Program to check if a person is eligible to vote:


<?php
$age = 20;

if ($age >= 18) {


echo "You are eligible to vote";
} else {
echo "You are not eligible to vote yet";
}
?>

Program to find the largest of three numbers:

<?php
$a = 10;
$b = 20;
$c = 15;

if ($a > $b && $a > $c) {


echo "$a is the largest number";
} elseif ($b > $a && $b > $c) {
echo "$b is the largest number";
} else {
echo "$c is the largest number";
}
?>

Program to determine the day of the week:

<?php
$day = "Monday";

switch ($day) {
case "Monday":
echo "Today is Monday";
break;
Kamadhenu BCA College -43-
case "Tuesday":
echo "Today is Tuesday";
break;
case "Wednesday":
echo "Today is Wednesday";
break;
case "Thursday":
echo "Today is Thursday";
break;
case "Friday":
echo "Today is Friday";
break;
case "Saturday":
echo "Today is Saturday";
break;
case "Sunday":
echo "Today is Sunday";
break;
default:
echo "Invalid day";
}
?>

Program to convert numeric month to its name:

<?php
$month = 3;

switch ($month) {
case 1:
echo "January";
break;
case 2:
echo "February";
break;
case 3:
echo "March";
break;
case 4:
echo "April";
break;
case 5:
echo "May";
break;
case 6:
echo "June";
break;
case 7:
echo "July";
break;
case 8:
echo "August";
break;
case 9:
echo "September";
Kamadhenu BCA College -44-
break;
case 10:
echo "October";
break;
case 11:
echo "November";
break;
case 12:
echo "December";
break;
default:
echo "Invalid month";
}
?>

Below is a PHP program with HTML form elements that accept an ID and password. Upon
submission, the program checks whether the provided ID and password match predefined
values. If they match, it displays a success message; otherwise, it displays an error message.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>

<?php
// Define predefined ID and password
$valid_id = "user123";
$valid_password = "password123";

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve values from form
$input_id = $_POST["id"];
$input_password = $_POST["password"];

// Check if ID and password match predefined values


if ($input_id === $valid_id && $input_password === $valid_password) {
echo "<p>Login successful. Welcome, $valid_id!</p>";
} else {
echo "<p>Invalid ID or password. Please try again.</p>";
}
}
?>

Kamadhenu BCA College -45-


</body>
</html>

This program consists of an HTML form that accepts an ID and password. Upon form submission
(by clicking the "Login" button), the PHP code checks whether the provided ID and password
match the predefined values (user123 for ID and password123 for password). If the provided
credentials match, it displays a success message; otherwise, it displays an error message.

?: Operator : The ? operator in PHP is known as the ternary operator. It's a shorthand way of
writing an if...else statement in a single line. It evaluates a condition and returns one value if
the condition is true, and another value if the condition is false.

Its syntax is: condition ? value_if_true : value_if_false

Here are two examples demonstrating the usage of the ternary operator:

1. Program to check if a number is positive or negative:


2. <?php
$number = 5;

$result = ($number >= 0) ? "Positive" : "Negative";

echo "The number $number is $result.";


?>

Program to check if a person is eligible to vote:

<?php
$age = 20;

$status = ($age >= 18) ? "Eligible" : "Not eligible";

echo "At age $age, you are $status to vote.";


?>

Looping, in programming, refers to the repetition of a block of code multiple times until
a certain condition is met. It allows you to automate repetitive tasks and process large
amounts of data efficiently.

Here's a basic breakdown of how looping works:

1. Initialization: You start by setting up any initial variables or conditions needed


for the loop.
2. Condition: You specify a condition that determines whether the loop should
continue running. If the condition is true, the loop executes; if it's false, the loop
terminates.

Kamadhenu BCA College -46-


3. Iteration: Within the loop, you typically perform some operations on data or
execute certain tasks. After each iteration, the loop updates its state (such as
incrementing a counter or moving to the next item in a list).
4. Termination: Once the condition becomes false, the loop stops executing, and
the program continues with the next line of code after the loop.

PHP supports several types of loops, including for, while, do-while, and foreach. Here's an
overview of each type:

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means
for loop is used when you already know how many times you want to execute a block of
code.

It allows users to put all the loop related statements in one place. See in the syntax given
below:

Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }

initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.

condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.

Increment/decrement - It increments or decrements the value of the variable.

Kamadhenu BCA College -47-


Flowchart

Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Kamadhenu BCA College -48-


Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass
parameters, it will execute infinite.

1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
Output:

1
2
3
4
.
.
.

Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

1. <?php
2. /* example 1 */
3.
4. for ($i = 1; $i <= 9; $i++) {
5. echo $i;
6. }
7. echo "</br>";
8.
9. /* example 2 */
10.
11. for ($i = 1; ; $i++) {
12. if ($i > 9) {
13. break;
14. }
Kamadhenu BCA College -49-
15. echo $i;
16. }
17. echo "</br>";
18.
19. /* example 3 */
20.
21. $i = 1;
22. for (; ; ) {
23. if ($i > 9) {
24. break;
25. }
26. echo $i;
27. $i++;
28. }
29. echo "</br>";
30.
31. /* example 4 */
32.
33. for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
34. ?>

Output:

123456789
123456789
123456789
123456789

PHP Nested For Loop


We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for
loop executes only when the outer for loop condition is found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop.
If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop
will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times
for 3rd outer loop).

Example

1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){

Kamadhenu BCA College -50-


4. echo "$i $j<br/>";
5. }
6. }
7. ?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop


PHP for each loop is used to traverse array elements.

Syntax

1. foreach( $array as $var ){


2. //code to be executed
3. }
4. ?>

Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }

There is one more syntax of foreach loop.

Syntax
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }

Kamadhenu BCA College -51-


Flowchart

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn

Practice programs :
Program to iterate over an array and display each element:

<?php
$colors = array("Red", "Green", "Blue");

foreach ($colors as $color) {


echo "Color: $color <br>";
}
?>

Kamadhenu BCA College -52-


Example 2:
PHP program to print associative array elements using foreach loop.

1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "alex_jtp@gmail.com",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>

Output:

Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male

Example 3:
Multi-dimensional array

1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
5. $a[0][1] = "Bob";
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {

Kamadhenu BCA College -53-


12. echo "$e2\n";
13. }
14. }
15. ?>

Output:

Alex Bob Camila Denial

Program to iterate over an associative array and display key-value pairs:

<?php
$student_scores = array("Alice" => 85, "Bob" => 92, "Charlie" => 78);

foreach ($student_scores as $name => $score) {


echo "$name's score is $score <br>";
}
?>

Program to iterate over a multidimensional array and display nested elements:

<?php
$books = array(
array("Title" => "The Great Gatsby", "Author" => "F. Scott Fitzgerald"),
array("Title" => "To Kill a Mockingbird", "Author" => "Harper Lee"),
array("Title" => "1984", "Author" => "George Orwell")
);

foreach ($books as $book) {


foreach ($book as $key => $value) {
echo "$key: $value <br>";
}
echo "<br>";
}
?>

In these examples:

• Example 1 iterates over a simple indexed array of colors and prints each color.
• Example 2 iterates over an associative array of student scores and prints each
student's name along with their score.
• Example 3 iterates over a multidimensional array of books, and for each book, it
iterates over the key-value pairs and prints each key-value pair.

Kamadhenu BCA College -54-


PHP While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block
of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from
the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is true, the
block of code will be executed.

Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart

PHP While Loop Example


1. <?php

Kamadhenu BCA College -55-


2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Example
Below is the example of printing alphabets using while loop.

1. <?php
2. $i = 'A';
3. while ($i < 'H') {
4. echo $i;

Kamadhenu BCA College -56-


5. $i++;
6. echo "</br>";
7. }
8. ?>

Output:

A
B
C
D
E
F
G

PHP Infinite While Loop


If we pass TRUE in while loop, it will be an infinite loop.

Syntax

1. while(true) {
2. //code to be executed
3. }

Example

1. <?php
2. while (true) {
3. echo "Hello K-BCA!";
4. echo "</br>";
5. }
6. ?>

Output:

Hello Hello K-BCA!


Hello Hello K-BCA!
Hello Hello K-BCA!
Hello Hello K-BCA!
.
.
.
.
.
Hello Hello K-BCA!
Hello Hello K-BCA!

Kamadhenu BCA College -57-


PHP do-while loop
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is recommended
to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the
code.

The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.

Syntax

1. do{
2. //code to be executed
3. }while(condition);

Flowchart

Example
Kamadhenu BCA College -58-
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the
do-while loop, it is must that the program should not contain any other statements after
the do-while loop. In this case, it will not generate any error.

1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>

Output:

Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!

Example
The following example will increment the value of $x at least once. Because the given
condition is false.

Kamadhenu BCA College -59-


1. <?php
2. $x = 1;
3. do {
4. echo "1 is not greater than 10.";
5. echo "</br>";
6. $x++;
7. } while ($x > 10);
8. echo $x;
9. ?>

Output:

1 is not greater than 10.


2

Difference between while and do-while loop


while Loop do-while loop
The while loop is also named as entry The do-while loop is also named as exit
control loop. control loop.
The body of the loop does not execute The body of the loop executes at least
if the condition is false. once, even if the condition is false.
Condition checks first, and then block Block of statements executes first and
of statements executes. then condition checks.
This loop does not use a semicolon to Do-while loop use semicolon to
terminate the loop. terminate the loop.

PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and
for-each loop. If you use break inside inner loop, it breaks the execution of inner loop
only.

The break keyword immediately ends the execution of the loop or switch structure. It
breaks the current flow of the program at the specified condition and program control
resumes at the next statements outside the loop.

The break statement can be used in all types of loops such as while, do-while, for, foreach
loop, and also with switch case.

Syntax
1. jump statement;
Kamadhenu BCA College -60-
2. break;

1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>

Output:

1
2
3
4
5

PHP Break: inside inner loop


The PHP break statement breaks the execution of inner loop only.

1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>
11. Output:
12. 1 1
13. 1 2
14. 1 3
15. 2 1
16. 2 2
17. 3 1
18. 3 2
19. 3 3

PHP Break: with array of string


1. <?php

Kamadhenu BCA College -61-


2. //declare an array of string
3. $number = array ("One", "Two", "Three", "Stop", "Four");
4. foreach ($number as $element) {
5. if ($element == "Stop") {
6. break;
7. }
8. echo "$element </br>";
9. }
10. ?>

Output:

One
Two
Three

You can see in the above output, after getting the specified condition true, break
statement immediately ends the loop and control is came out from the loop.

PHP Break: switch statement without break


It is not essential to break out of all cases of a switch statement. But if you want that only
one case to be executed, you have to use break statement.

1. <?php
2. $car = 'Mercedes Benz';
3. switch ($car) {
4. default:
5. echo '$car is not Mercedes Benz<br>';
6. case 'Orange':
7. echo '$car is Mercedes Benz';
8. }
9. ?>

Output:

$car is not Mercedes Benz


$car is Mercedes Benz

PHP continue statement

Kamadhenu BCA College -62-


The PHP continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.

The continue statement is used within looping and switch control structure when you
immediately jump to the next iteration.

The continue statement can be used with all types of loops such as - for, while, do-while, and
foreach loop. The continue statement allows the user to skip the execution of the code for the
specified condition.

Syntax
The syntax for the continue statement is given below:

1. jump-statement;
2. continue;

PHP Continue Example with for loop


Example

In the following example, we will print only those values of i and j that are same and skip
others.

1. <?php
2. //outer loop
3. for ($i =1; $i<=3; $i++) {
4. //inner loop
5. for ($j=1; $j<=3; $j++) {
6. if (!($i == $j) ) {
7. continue; //skip when i and j does not have same values
8. }
9. echo $i.$j;
10. echo "</br>";
11. }
12. }
13. ?>

Output:

11
22
33

PHP continue Example with array of string


Kamadhenu BCA College -63-
Example

The following example prints the value of array elements except those for which the
specified condition is true and continue statement is used.

1. <?php
2. $number = array ("One", "Two", "Three", "Stop", "Four");
3. foreach ($number as $element) {
4. if ($element == "Stop") {
5. continue;
6. }
7. echo "$element </br>";
8. }
9. ?>

Output:

One
Two
Three
Four

Arrays in PHP are versatile and powerful data structures used to store multiple values under a
single variable name. PHP supports various types of arrays, including indexed arrays, associative
arrays, and multidimensional arrays. Here's an overview of each type:

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

Kamadhenu BCA College -64-


1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:

1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:

Season are: summer, winter, spring and autumn


File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>

Output:

Season are: summer, winter, spring and autumn


Click me for more details...

Kamadhenu BCA College -65-


PHP Associative Array
We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

Kamadhenu BCA College -66-


PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix
which is represented by row * column.

Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
PHP Multidimensional Array Example

Let's see a simple example of PHP multidimensional array to display following tabular data. In
this example, we are displaying 3 rows and 3 columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

File: multiarray.php

1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
Kamadhenu BCA College -67-
13. echo "<br/>";
14. }
15. ?>

Output:

1 sonoo 400000
2 john 500000
3 rahul 300000

Program example :
Program to display elements of an indexed array:

<?php
$colors = array("Red", "Green", "Blue");

foreach ($colors as $color) {


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

2. Program to display elements of an associative array:

<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");

foreach ($person as $key => $value) {


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

Program to find the sum of elements in an indexed array:

<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = 0;

foreach ($numbers as $number) {


$sum += $number;
}

echo "Sum of elements: $sum";


?>

These examples demonstrate different array operations in PHP:

• Example 1 displays the elements of an indexed array using a foreach loop.

Kamadhenu BCA College -68-


• Example 2 displays the key-value pairs of an associative array using a foreach
loop.
• Example 3 calculates the sum of elements in an indexed array using a foreach loop
and a variable to accumulate the sum

Below is a comparison of indexed arrays and associative arrays in PHP presented in


tabular format:

Feature Indexed Array Associative Array


Contains a collection of elements indexed Contains key-value pairs where each value is
Definition by integers starting from 0. associated with a specific key.
$array = array(value1, value2, $array = array(key1 => value1, key2 => value2,
...);<br>or<br> $array = [value1, ...);<br>or<br> $array = [key1 => value1, key2 =>
Declaration value2, ...]; value2, ...];
Accessing Accessed using numerical indices starting
Elements from 0. Accessed using keys instead of numerical indices.
$person = array("name" => "John", "age" => 30, "city"
Example $colors = array("Red", "Green", "Blue"); => "New York");
Looping Typically looped through using numeric Typically looped through using foreach loop,
Through indices with for or foreach loop. accessing key-value pairs.
Suitable for storing ordered collections of
data where the order of elements Suitable for storing data with associated keys where
Usage matters. you need to access values using specific identifiers.
Storing data with specific labels or attributes, such as
Storing lists of items like colors, numbers, user information, configuration settings, or
Use Case or any ordered collection. associative data structures.

This table provides a clear comparison between indexed arrays and associative arrays in
PHP, outlining their differences in declaration, access, usage, and use cases.

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed, associative and
multidimensional arrays.

Syntax

Kamadhenu BCA College -69-


1. array array ([ mixed $... ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>

Output:

Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>

Output:

Kamadhenu BCA College -70-


Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
3) PHP array_chunk() function
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you
can divide array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.

Kamadhenu BCA College -71-


Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
winter

Kamadhenu BCA College -72-


summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if search
is successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it
returns the matching elements of two array.

Syntax

1. array array_intersect ( array $array1 , array $array2 [, array $... ] )

Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

Kamadhenu BCA College -73-


sonoo
smith

PHP Include Files


The include (or require) statement takes all the text/code/markup that
exists in the specified file and copies it into the file that uses the include
statement.

Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.

PHP include and require Statements


It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

• require will produce a fatal error (E_COMPILE_ERROR) and stop the


script
• include will only produce a warning (E_WARNING) and the script will
continue

So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file
is accidentally missing.

Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header
needs to be updated, you can only update the header include file.

Syntax
include 'filename';

or

require 'filename';

Kamadhenu BCA College -74-


PHP include Examples
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . kamadhenuacademy.com</p>";
?>

To include the footer file in a page, use the include statement:

<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

Welcome to my home page!


Some text.

Some more text.

Copyright © 1999-2024 kamadhenuacademy.com

Example 2
Assume we have a standard menu file called "menu.php":

<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done
(we are using a <div> element so that the menu easily can be styled with CSS
later):

Kamadhenu BCA College -75-


Example
<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP 7 Tutorial
Welcome to my home page!
Some text.

Some more text.

Example 3
Assume we have a file called "vars.php", with some variables defined:

<?php
$color='red';
$car='BMW';
?>

Then, if we include the "vars.php" file, the variables can be used in the calling
file:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php include 'vars.php';
echo "I have a $color $car.";
?>

</body>
</html>

Welcome to my home page!


I have a red BMW.
Kamadhenu BCA College -76-
PHP include vs. require
The require statement is also used to include a file into the PHP code.

However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will
continue to execute:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Welcome to my home page!


I have a .

If we do the same example using the require statement, the echo statement will
not be executed because the script execution dies after the require statement
returned a fatal error:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Welcome to my home page!

Kamadhenu BCA College -77-


In PHP, both require and include are used to include and evaluate the contents of
another PHP file within the current PHP file. However, there are differences in how they
handle errors and their behavior when the included file is not found.

Here's a comparison of require and include:

1. Behavior when File Not Found:


• require: If the specified file is not found, PHP will generate a fatal error and
halt the script execution.
• include: If the specified file is not found, PHP will generate a warning but
will continue to execute the script.
2. Error Handling:
• require: It is considered a critical part of the script. If the file cannot be
included, a fatal error occurs, and script execution stops.
• include: It is not considered critical. If the file cannot be included, a warning
is issued, but the script continues to execute.
3. Usage:
• require: Use require when the included file is essential for the script's
functionality, and its absence should result in script termination.
• include: Use include when the included file is not essential, and its absence
can be handled gracefully by the script.

PHP Casting
Sometimes you need to change a variable from one data type into another,
and sometimes you want a variable to have a specific data type. This can be
done with casting.

In PHP, casting refers to converting a value from one data type to another. There are two
types of casting: implicit casting and explicit casting.

1. Implicit Casting:
• Implicit casting occurs automatically by PHP when a value is used in a
context that expects a different data type.
• PHP tries to convert the value to the expected data type without any
explicit instruction from the programmer.
• For example, when performing arithmetic operations or comparisons
involving different data types, PHP performs implicit casting to ensure
compatibility.

$x = 10; // integer
Kamadhenu BCA College -78-
$y = 5.5; // float

$result = $x + $y; // Implicit casting: $x is converted to float before addition


echo $result; // Output: 15.5
Explicit Casting:
• Explicit casting involves the programmer explicitly converting a value from one
data type to another using casting operators or functions.
• PHP provides several casting operators and functions for explicit casting, such as
(int), (float), (string), (array), (object), etc.
• Explicit casting allows precise control over how values are converted between
data types.
$x = "10"; // string

$intX = (int) $x; // Explicit casting to integer


echo $intX; // Output: 10

In the example above, (int) is used to explicitly cast the string value $x to an integer. Similarly,
(float), (string), (array), and (object) can be used for explicit casting to float, string, array,
and object types respectively.

Change Data Type


Casting in PHP is done with these statements:

• (string) - Converts to data type String


• (int) - Converts to data type Integer
• (float) - Converts to data type Float
• (bool) - Converts to data type Boolean
• (array) - Converts to data type Array
• (object) - Converts to data type Object
• (unset) - Converts to data type NULL

Cast to String
To cast to string, use the (string) statement:

$a = 5; // Integer

$b = 5.34; // Float

$c = "hello"; // String

$d = true; // Boolean

$e = NULL; // NULL

Kamadhenu BCA College -79-


$a = (string) $a;

$b = (string) $b;

$c = (string) $c;

$d = (string) $d;

$e = (string) $e;

//To verify the type of any object in PHP, use the var_dump() function:

var_dump($a);

var_dump($b);

var_dump($c);

var_dump($d);

var_dump($e);

output :

string(1) "5"
string(4) "5.34"
string(5) "hello"
string(1) "1"
string(0) ""

Note that when casting a Boolean into string it gets the value "1", and when casting NULL into string
it is converted into an empty string "".

Cast to Integer
To cast to integer, use the (int) statement:

$a = 5; // Integer

$b = 5.34; // Float

$c = "25 kilometers"; // String

$d = "kilometers 25"; // String

$e = "hello"; // String

$f = true; // Boolean

Kamadhenu BCA College -80-


$g = NULL; // NULL

$a = (int) $a;

$b = (int) $b;

$c = (int) $c;

$d = (int) $d;

$e = (int) $e;

$f = (int) $f;

$g = (int) $g;

Output :
int(5)
int(5)
int(25)
int(0)
int(0)
int(1)
int(0)

Note that when casting a string that starts with a number, the (int) function uses that number. If it
does not start with a number, the (int) function convert strings into the number 0.

Cast to Float
To cast to float, use the (float) statement:

$a = 5; // Integer

$b = 5.34; // Float

$c = "25 kilometers"; // String

$d = "kilometers 25"; // String

$e = "hello"; // String

$f = true; // Boolean

$g = NULL; // NULL

$a = (float) $a;
Kamadhenu BCA College -81-
$b = (float) $b;

$c = (float) $c;

$d = (float) $d;

$e = (float) $e;

$f = (float) $f;

$g = (float) $g;

Ouput :
float(5)
float(5.34)
float(25)
float(0)
float(0)
float(1)
float(0)

Note that when casting a string that starts with a number, the (float) function uses that number. If it
does not start with a number, the (float) function convert strings into the number 0.

Cast to Boolean
To cast to boolean, use the (bool) statement:

$a = 5; // Integer

$b = 5.34; // Float

$c = 0; // Integer

$d = -1; // Integer

$e = 0.1; // Float

$f = "hello"; // String

$g = ""; // String

$h = true; // Boolean

$i = NULL; // NULL

$a = (bool) $a;

$b = (bool) $b;

Kamadhenu BCA College -82-


$c = (bool) $c;

$d = (bool) $d;

$e = (bool) $e;

$f = (bool) $f;

$g = (bool) $g;

$h = (bool) $h;

$i = (bool) $i;

Output :
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)

If a value is 0, NULL, false, or empty, the (bool) converts it into false, otherwise true. Even -1
converts to true.

Cast to Array
To cast to array, use the (array) statement:

$a = 5; // Integer

$b = 5.34; // Float

$c = "hello"; // String

$d = true; // Boolean

$e = NULL; // NULL

$a = (array) $a;

$b = (array) $b;

$c = (array) $c;

$d = (array) $d;

$e = (array) $e;

Kamadhenu BCA College -83-


Output

array(1) {
[0]=>
int(5)
}
array(1) {
[0]=>
float(5.34)
}
array(1) {
[0]=>
int(0)
}
array(1) {
[0]=>
int(-1)
}
array(1) {
[0]=>
float(0.1)
}
array(1) {
[0]=>
string(5) "hello"
}
array(1) {
[0]=>
string(0) ""
}
array(1) {
[0]=>
bool(true)
}
array(0) {
}

When converting into arrays, most data types converts into an indexed array with one element.

NULL values converts to an empty array object.

Cast to NULL
To cast to NULL, use the (unset) statement:

Kamadhenu BCA College -84-


Example
$a = 5; // Integer

$b = 5.34; // Float

$c = "hello"; // String

$d = true; // Boolean

$e = NULL; // NULL

$a = (unset) $a;

$b = (unset) $b;

$c = (unset) $c;

$d = (unset) $d;

$e = (unset) $e;

Ouput :
NULL
NULL
NULL
NULL
NULL

Kamadhenu BCA College -85-

You might also like