KEMBAR78
PHPTRB | PDF | Php | World Wide Web
0% found this document useful (0 votes)
56 views36 pages

PHPTRB

Uploaded by

Sobiya Ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views36 pages

PHPTRB

Uploaded by

Sobiya Ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

SYLLABUS

Basics of PHP:
Evaluation of PHP, Basic Syntax, Defining variable and constant, PHP Data type,
Operator and Expression, Making Decisions, Doing Repetitive task with looping,
Mixing Decisions and looping with HTML.

Functions:
Defining a function, Call by value and Call by reference, Recursive function.

String Handling:
Creating and accessing, String Searching and Replacing String, Formatting String,
String Related Library functions.

Array:
 Anatomy of an Array, Index based and Associative array, Accessing array, Element
Looping with Index based array, Looping with associative array.

Working with file and Directories:


Understanding file and directory, Opening and closing a file, Copying, renaming
and deleting a file, working with directories, Creating and deleting folder, File
uploading and downloading.

MySQL:
MySQL database connection, Creating a table with key constraints, dropping
a table, adding, retrieving, updating data, deleting data, Performing additional
queries (Joins and subqueries), Connecting to MySQL, Accessing MySQL using
PHP, Querying MySQL database with PHP.
Introduction to PHP
Introduction
The term PHP is an acronym
for – Hypertext Preprocessor. PHP
is a server-side scripting language
designed specifically for web
development. It is an open-source
which means it is free to download
and use. It is very simple to learn
and use. The file extension of PHP is
“.php”.

What is PHP?
PHP is a server-side scripting
language created primarily for web
development but it is also used as a
general-purpose programming
language. Unlike client-side
languages like JavaScript, which are
executed on the user’s browser, PHP
scripts run on the server. The results
are then sent to the client’s web
browser as plain HTML.

1
interpreted language and it does not require a
compiler. The language quickly evolved and was
given the name “PHP,” which initially named was
“Personal Home Page.”
• PHP 3 (1998): The first version considered
suitable for widespread use.
• PHP 4 (2000): Improved performance and
the introduction of the Zend Engine.
• PHP 5 (2004): Added object-oriented
programming features.
• PHP 7 (2015): Significant performance
improvements and reduced memory usage.

• PHP 8 (2020): Introduction of Just-In-Time


History of PHP
(JIT) compilation, further enhancing
PHP was introduced by Rasmus
performance.
Lerdorf in 1994, the first version and
participated in the later versions. It is an
PHP Features results in faster processing speed and better
performance.
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
Performance: HTML tags and script.
PHP script is executed much faster than
those scripts which are written in other Platform Independent:
languages such as JSP and ASP. PHP uses its PHP is available for WINDOWS, MAC,
own memory, so the server workload and LINUX & UNIX operating system. A PHP
loading time is automatically reduced, which application developed in one OS can be easily
executed in other OS also.

2
Database Support: How PHP Works?
PHP supports all the leading databases PHP scripts are executed on the server. Here’s a
such as MySQL, SQLite, ODBC, etc. typical flow of how PHP works:
• A user requests a PHP page via their web
Error Reporting - browser.
PHP has predefined error reporting • The server processes the PHP code. The PHP
constants to generate an error notice or warning at interpreter parses the script, executes the code,
runtime. E.g., E_ERROR, E_WARNING, and generates HTML output.
• The server sends the generated HTML back to
E_STRICT, E_PARSE.
the client’s browser, which renders the web
Loosely Typed Language: page.
PHP allows us to use a variable without This server-side processing allows for dynamic
declaring its datatype. It will be taken content generation and ensures that sensitive code
automatically at the time of execution based on the is not exposed to the client.
type of data it contains on its value. Syntax
Web servers Support: <?php
// PHP code goes here
PHP is compatible with almost all local
?>
servers used today like Apache, Netscape,
Microsoft IIS, etc. Basic Example of PHP
HTML
Security: <!DOCTYPE html>
PHP is a secure language to develop the <html>
website. It consists of multiple layers of security to <head>
prevent threads and malicious attacks. <title>PHP Hello World</title>
Control: </head>
Different programming languages require <body>
long script or code, whereas PHP can do the same <?php echo "Hello, World! This is PHP code";?>
work in a few lines of code. It has maximum control </body>
over the websites like you can make changes easily </html>
whenever you want. Output:
Hello, World! This is PHP code
A Helpful PHP Community:
It has a large community of developers who PHP Installation and Configuration
regularly updates documentation, tutorials, online To get started with PHP, you need to set up a local
help, and FAQs. Learning PHP from the environment. Here’s a simple guide:
communities is one of the significant benefits. • Install a Web Server: Apache or Nginx are
popular choices.
Interesting fact: PHP Was Created by a • Install PHP: Download and install the latest
Programmer Who Didn’t Know What He Was
version of PHP from the official PHP website.
Doing
• Rasmus Lerdorf, the creator of PHP, originally wrote • Install a Database: MySQL or MariaDB are
it in 1993 as a simple set of scripts to track visitors to commonly used with PHP.
his online resume. The first version was called • Configure PHP: Update the php.ini file to
"Personal Home Page Tools", which later evolved
into PHP/FI (Personal Home Page/Form configure PHP settings as needed.
Interpreter). For beginners, a complete package like XAMPP
• He didn’t intend for it to become a full-fledged (Windows) or MAMP (macOS) is recommended,
programming language. In fact, PHP was initially just
a collection of CGI (Common Gateway Interface)
as it comes bundled with Apache, PHP, and
binaries for tracking web visitors. MySQL.

3
Interesting fact: PHP Is Everywhere the backend of a website. For example, PHP can
• Over 75% of websites on the internet use
receive data from forms, generate dynamic page
PHP in some capacity. This includes some content, can work with databases, create sessions,
of the most popular websites in the world send and receive cookies, send emails, etc. There
like Facebook, WordPress, Wikipedia, and are also many hash functions available in PHP to
Tumblr. encrypt users’ data which makes PHP secure and
• It’s used for creating dynamic web pages, reliable to be used as a server-side scripting
handling forms, managing databases, and language. So these are some of PHP’s abilities that
more make it suitable to be used as a server-side
scripting language.
Applications of PHP Even if the above abilities do not convince
you of PHP, there are some more features of PHP.
PHP can run on all major operating systems like
Windows, Linux, Unix, Mac OS X, etc. Almost all
of the major servers available today like Apache
supports PHP. PHP allows using a wide range of
databases. And the most important factor is that it
is free to use and download and anyone can
download PHP from its

Advantages of PHP
PHP is versatile and can be used in a variety of web
development scenarios, including:
• Content Management Systems
(CMS): Many popular CMSs like WordPress,
Joomla, and Drupal are built with PHP.
• E-commerce Platforms: PHP is commonly
used to develop e-commerce websites due to
its database integration capabilities.
• GUI-based Apps: PHP is also used to create
graphical user interface-based applications for
desktops. Several tools, such as PHP-GTK 2
and ZZEE PHP GUI, are used for scripting
client-side GUI-based apps.
• Data Representation: The developers often
• Open Source: PHP is an open-source
use PHP for data representation purposes. language, meaning it is freely available for
Charts, scatter-dot plots, graphs, etc., anyone to use and distribute. This openness has
• Image Processing & Graphics fostered a large and active community of
Design: popularly used in the processing of developers who continuously contribute to its
graphics and images. Certain image processing growth, improvement, and feature
development.
libraries such as Imagine, ImageMagick, and
• Easy to Learn: The syntax of PHP is quite
GD library can be integrated with PHP for similar to C and other programming languages.
various purposes ranging from resizing and This makes PHP relatively easy to learn,
rotating to cropping and thumbnail creation. especially for developers who already have
Why should we use PHP? some programming experience. Beginners find
PHP can actually do anything related to it approachable due to its straightforward
server-side scripting or more popularly known as syntax and extensive online resources.

4
• Web Integration: PHP is designed specifically Disadvantages of PHP
for web development and is embedded within
HTML. It seamlessly integrates with various
web technologies, facilitating the creation of
dynamic and interactive web pages.
• Database Support: PHP has excellent
support for various databases, including
MySQL, PostgreSQL, SQLite, and more. This
makes it easy to connect and interact with
databases, a crucial aspect of many web
applications.
• Cross-Platform Compatibility: PHP is • Inconsistency: PHP has been criticized for
platform-independent and runs on various inconsistencies in function names and
operating systems, including Windows, Linux, parameter orders. This can lead to confusion
macOS, and others. This ensures compatibility for developers, especially when working with a
across different environments. mix of older and newer functions.
• Large Community and • Security Concerns: If not handled properly,
Documentation: PHP has a vast and active PHP code may be susceptible to security
community of developers. The abundance of vulnerabilities, such as SQL injection and cross-
online resources, tutorials, and documentation site scripting (XSS). Developers need to be
makes it easier for developers to find solutions cautious and follow best practices to secure
and seek help when needed. PHP applications.
• Frameworks and CMS: There are popular • Performance: While PHP performs well for
PHP frameworks like Laravel, Symfony, and many web applications, it may not be as fast as
CodeIgniter, which provide pre-built modules some compiled languages like C or Java.
and features, aiding in rapid development. However, advancements and optimizations in
Additionally, PHP supports widely used recent versions have improved performance.
content management systems (CMS) like • Lack of Modern Features: Compared to
WordPress and Joomla. newer languages, PHP may lack some modern
• Server-Side Scripting: PHP scripts are language features. However, recent versions of
executed on the server, reducing the load on PHP have introduced improvements and
the client’s side. This server-side scripting features to address this concern.
capability is crucial for generating dynamic • Scalability Challenges: PHP can face
content and performing server-related tasks. challenges when it comes to scaling large and
• Community Support: The PHP community complex applications. Developers may need to
actively contributes to the language’s adopt additional tools or frameworks to
development, ensuring regular updates, address scalability issues.
security patches, and improvements.

Success is not for the ones who quit, but for those who persist."

5
• Not Suitable for Large-Scale Better run-time performance and improved
Applications: While PHP is suitable for small extension API with web server abstraction layers
to medium-sized projects, it might not be the and the methodology of compile first and execute
best choice for extremely large and complex later were some of the reasons which made PHP
applications where more structured languages the base for building CMS like WordPress in 2003.
might be preferred. Over time, with each update, improvements in
• Limited Object-Oriented Programming error handling, performance improvements almost
(OOP) Support: Although PHP supports OOP, twice as the previous versions and several more
its implementation has been criticized for not features led to a continuous increase in the
being as robust as in some other languages. popularity of the language as the preferred web
However, recent versions have introduced development technology.
improvements to enhance OOP capabilities.
Basic Syntax of PHP
Evaluation of PHP
PHP, a powerful server-side scripting
HP or Hypertext Preprocessor was developed language used in web development. It’s simplicity
by an employed Danish programmer, Rasmus and ease of use makes it an ideal choice for
Lerdorf out of Toronto in Canada in 1994 and beginners and experienced developers. This
released to the public in 1995 with the name article provides an overview of PHP syntax. PHP
Personal Home Page tools. It was then rewritten in scripts can be written anywhere in the document
1996 by Zeev Suraski and Andi Gutman who within PHP tags along with normal HTML.
launched it as PHP3. In 2000, PHP4 was released
PHP code is executed between PHP tags,
incorporated into a scripting engine followed by 3
allowing the integration of PHP code within
more major-version and few subversions until the
HTML. The most common PHP tag is <?php …
latest version PHP7.0 was released in 2015. It
?>, which is used to enclose PHP code. The <?php
gained popularity over the years owing to it being
….?>is called Escaping to PHP.
open source and allowing other programmers to
use the language on their own pages and today
controls over 80% of websites across the globe.
PHP has emerged as one of the highly popular
server-side scripting languages owing to its
The script starts with <?php and ends
flexibility, innovative features and it is the fastest
with ?>. These tags are also called ‘Canonical PHP
resource present for creating database-enabled
tags’. Everything outside of a pair of opening and
dynamic websites. PHP includes a well-organized
closing tags is ignored by the PHP parser. The open
code that is easily embedded into HTML code and
and closing tags are called delimiters. Every PHP
all features and updates to the language are
command ends with a semi-colon (;).
available free of cost. In comparison to the other
languages, troubleshooting and debugging issues
Basic Example of PHP
is easier in PHP. Moreover, it supports major
operating systems like Windows, Linux, Unix, Mac
OS, etc and also supports enterprise and web
servers like Microsoft IIS, Netscape, Apache, etc.
These features of PHP made it increasingly the
choice for web developers when designing
Output
complex but attractive websites during a short
Hello, world!
span of time.
6
echo $Var;
Embedding PHP in HTML // Error: Undefined variable $var
PHP code can be embedded within HTML echo $var;
using the standard PHP tags. In this example, the ?>
<?php echo “Hello, PHP!”; ?> statement
dynamically inserts a heading into the HTML Interesting fact: PHP is Not Just for
document. Websites
HTML While PHP is mostly associated with web
development, it can be used for other tasks as
well. PHP has been used for creating
command-line scripts, running background
tasks, or even building desktop applications
(though it's not commonly used for that
purpose).

Comments in PHP
Comments are used to make code more
readable by explaining the purpose of specific
code blocks. Comments are ignored by the PHP
Did You Know PHP is Case- interpreter.
insensitive for Functions? Single Line Comment
• PHP function names are case-insensitive.
Whether you write echo, ECHO, or Echo, As the name suggests, these are single line
the result will be the same. However, it's or short relevant explanations that one can add to
best practice to follow standard their code. To add this, we need to begin the line
conventions and use lowercase for with (//) or (#).
function names. <?php
// This is a single line comment
SGML or Short HTML Tags // These cannot be extended to more lines
These are the shortest option to initialize a PHP echo "Hello World!";
code. The script starts with <? and ends with ?>. # This is also a single line comment
?>
This will only work by setting
the short_open_tag setting in the php.ini file to ‘on’. Output
Example: Hello World!
<?php Multi-Line or Multiple Line Comment
// Here echo command will only work if It is used to accommodate multiple lines
// setting is done as said before with a single tag and can be extended to many lines
echo "Hello, world!"; as required by the user. To add this, we need to
?> begin and end the line with (/*…*/)
Output
Hello, world!

Case Sensitivity
PHP is partially case-sensitive-
• Keywords (like if, else, while, echo) are not
case-sensitive.
• Variable names are case-sensitive. Output
Example:
Hello World!
<?php
$Var = "Hello Teacher";
// Outputs: Hello Teacher
7
Variables and Data Types • NULL: A special type representing a variable
Variables are used to store data that can be with no value.
manipulated within PHP. They are declared using • Resource: A special type that holds a reference
the $ symbol followed by the variable name. to external resources (like database
connections).
Declaring Variables
Variables are created by assigning a value to them
Blocks in PHP
using the assignment operator (=).
In PHP, multiple statements can be executed
simultaneously (under a single condition or loop)
by using curly-braces ({}). This forms a block of
statements that gets executed simultaneously.
<?php
$var = 50;
Data Types if ($var > 0) {
PHP supports several data types, including: echo ("Positive as \n");
• String: A sequence of characters. echo ("greater than 0");
• Integer: Whole numbers. }
• Float (Double): Numbers with a decimal ?>
point. Output
• Boolean: Represents true or false. Positive as
• Array: A collection of values. greater than 0
• Object: An instance of a class.

8
Practice Questions
1. What does PHP stand for? form data after submitting an HTML form?
A) Personal Home Page A) $_POST B) $_GET
B) PHP Hypertext Preprocessor C) $_REQUEST D) All of the above
C) Private Home Page
10. In PHP, how do you create an associative
D) Public Hypertext Processor
array?
2. Which of the following is a correct way to A) $arr = array("key1" => "value1", "key2" =>
start a PHP code block? "value2");
A) <php> B) <?php B) $arr = ["key1" => "value1", "key2" => "value2"];
C) <script> D) <html> C) Both A) and B)
D) None of the above
3. Which function is used to output data to the
browser in PHP? 11. What is one of the primary advantages of
A) echo() B) print() using PHP for web development?
C) output() D) Both A) and B) A) It requires extensive configuration
B) It is highly compatible with various databases
4. What is the default file extension for PHP
C) It has limited community support
files?
D) It only runs on Windows servers
A) .html B) php C) txt D) xml
12. Which of the following is a disadvantage of
5. Which of the following is NOT a valid variable
PHP?
name in PHP?
A) It is completely free to use
A) $myVariable B) $_myVar
B) It can lead to security vulnerabilities if not coded
C) $1stVariable D) $my_var
properly
6. What is the correct way to create a constant C) It supports only object-oriented programming
in PHP? D) It has a very steep learning curve
A) define("CONSTANT_NAME", "value");
13. In which scenario is PHP commonly applied?
B) const CONSTANT_NAME = "value";
A) Desktop application development
C) Both A) and B)
B) Creating static websites without interactivity
D) None of the above
C) Server-side scripting for dynamic web applications
7. Which of the following statements is true D) Developing mobile applications exclusively
about PHP?
14. One of the reasons PHP is popular among
A) PHP is a server-side scripting language.
developers is its:
B) PHP can be embedded in HTML.
A) Lack of frameworks
C) PHP is platform-independent.
B) Rich set of built-in functions
D) All of the above.
C) Requirement for high-end servers
8. What is the purpose of the PHP require() D) Incompatibility with HTML
function?
15. What is a typical application of PHP in a
A) To include a file only once.
content management system (CMS)?
B) To include a file and terminate the script if it fails.
A) Handling client-side animations
C) To include a file and continue execution if it fails.
B) Managing database interactions for content storage
D) To create a new PHP variable.
C) Writing operating system-level scripts
9. Which PHP super global is used to collect
D) Developing hardware drivers
Ans : 1-b,2-b,3-d,4-b,5-c,6-c,7-d,8-b,9-d,10-c,11-b,12-b,13-c,14-b,15-b

9
2. Variables and Constants in PHP
Defining Variables • A variable takes a datatype according to the
value assigned to it.
A PHP variable is a name given to a
• Since we don’t have to specify datatypes for
memory address that holds data. The basic
PHP variables, PHP is called as loosely typed
method to declare a PHP variable is by using a $
language.
sign which is followed by the variable name. A
variable helps the PHP code to store information in Exam Points PHP Variables Don’t Need Type
Declarations:
the middle of the program. If we use a variable
• PHP is a loosely typed language, which
before it is assigned then it already has a default means you can change a variable’s type at
value stored in it. Some of the data types that we any point. For example, a variable that
can use to construct a variable are integers, initially holds an integer can later hold a
doubles, and boolean. string or an array.

Example: Scope of variables:


<?php Variables can be declared anywhere in the
$txt = "Hello"; program.
$x = 5; php Scope of a variable is a part of the program
$y = 10.5; where the variable is accessible.
Copy code
echo $txt;
PHP has three different variable scopes:
echo "<br>"; $value = 100; // Integer
• Local
echo $x; $value = "Hello"; // Now a String
• Global
echo "<br>";
• Static
echo $y;
?> Local scope:
Output A variable declared within a function has a
Hello local scope and can be accessed within a function
5 only.A function is a small program performing a
10.5 particular task which is called when required.
Rules for variable names:
Global scope:
• Variable names in PHP start with a
A variable declared outside a function has a
dollar ($) sign followed by the variable name.
global scope and can be accessed outside the
• Variable name can contain alphanumeric
function only.Actually, global variables can be
characters and underscore (_).
accessed anywhere using the global keyword.
• Variable names must start with a letter or an
underscore (_). (For eg: $abc, $x1, $_g, $abc_1 Static scope:
etc.) A variable declared with static keyword is said
• Variable names cannot start with a number. to have static scope within the function.
• Variable names are case-sensitive. (for eg: $x Normally when variables are executed, they lose
and $X are treated as two different variables.) their values or memory.
• In PHP we don’t use any command to declare But when a variable is declared as static, it
variables. doesn’t lose its value. It remains static within
• A variable is created as soon as you assign a multiple function calls.
value to it. (Content Developed by Pro.fessor
Ac.ademy)

10
Variable declaration: • Both the value of $x and $y are printed in the
Variable is declared as follows: function myfun() as well as outside the function.
$variable_name=value; • The function myfun() needs to be called for
Example of variable declaration is given below: execution as done in the statement myfun().
$x=5;
$x is a variable and 5 is a value assigned to $x
variable using assignment operator (=). The
assignment operator assigns the right hand side
• You will get the following error shown in the
value to the left hand side variable in an
figure below:
expression.
• This error occurs because the global variable
The variable name can be just alphabets or they
$x is not accessible in the function myfun().
can be some descriptive names
• And local variable $y of function myfun() is not
like $school_name, $names, $games etc.
accessible outside the function.
In PHP we can print a value of variable using an • Now just comment the following statements
echo statement as follows: given below in the code:
<?php • echo "Value of var x inside myfun = ".$x;
$x=10; • echo "Value of var y outside myfun = ".$y;
echo $x; o We will get the following output:
?>
Output
10

Demonstration of Global Scope of variables: • But meaning of global is accessible


Write the following code in index.php file everywhere, and here we see that the global
and test it by putting it in the newly created variable $x is not accessible inside the function
folder var_constant in htdocs folder of xampp myfun().
folder. • We can make it accessible by using keyword
The code is as follows: global before the variable $x inside function
<?php myfun().
$x = 10; // Global variable It is shown below:
function myfun() <?php
{ $x=10; //global variable
global $x; // Declare $x as global //echo $x;
$y = 20; // Local variable function myfun()
echo "Value of var x inside myfun = " . $x; {
echo "<br>"; global $x; //accessing global variable inside
echo "Value of var y inside myfun = " . $y; function
echo "<br>"; $y=20; //local variable
}
myfun(); echo "Value of var x inside myfun = ".$x;
echo "Value of var x outside myfun = " . $x; echo "<br>";
echo "<br>"; echo "Value of var y inside myfun = ".$y;
?> echo "<br>";
Here, we have declared a global variable and a }
local variable in the function myfun(). myfun();
echo "Value of var x outside myfun = ".$x;
11
echo "<br>"; static_eg();
//echo "Value of var y outside myfun = ".$y; static_eg();
?> static_eg();
?>
• In the above code we have a statement global • Here, we see that we have a
$x; written inside the function myfun(). This function static_eg() that contains two variables
allows access to global variable inside the viz. $x and $y.
function. • $x is a simple local variable and $y is a local
• Now let us see the output of the above code: variable but also a static variable.
• Both are initialized to zero.
• After printing the values of both the variables
using echo statement, they are incremented
• The statement Value of var x inside myfun = each time.
10 proves that now the value of $x is accessible • The function static_eg() is called 4 times.
in function myfun(). • The output of the above code is given below:
• The statement
• echo "Value of var y outside myfun = ".$y;
• is commented in the program because it will
give error since the local variables are not • Here, we can see that the value of variable $x is
accessible outside the function. zero (0) every time and the value of variable $y
• You might have noticed a period (.) in the echo is incremented by 1 each time.
statement. For example let us see the following
Interesting Facts: You Can Use unset() to
statement: Destroy Variables:
• echo "Value of var y outside myfun = ".$y; • PHP allows you to destroy variables with
• Here we have a period (.) in between a the unset() function. After calling unset(),
string “Value of var y outside myfun = the variable is no longer available.
php
“ and variable $y. This period is used for
concatenating/joining two values. Copy code
• Demonstration of Static Scope of variables: $x = 10;
• We discussed that static scope means the value unset($x); // $x is now destroyed
of a variable is retained within multiple function
calls. • This is because a simple variable loses its
• Let us try to demonstrate it. value once it comes out of the block it is defined
• Write the following code in index.php file by in, but a static variable retains its value each time.
commenting all the previous code:
<?php Defining Constants
function static_eg() PHP Constants are the identifiers that
{ remain the same. Usually, it does not change during
$x=0; the execution of the script. They are case-sensitive.
static $y=0; By default, constant identifiers are always
uppercase. Usually, a Constant name starts with an
echo "non-static var x = $x &nbsp;&nbsp; static var
underscore or a letter which is followed by a
y = $y <br>"; number of letters and numbers. They are no need
$x++; to write a constant with the $ sign.
$y++; The constant() function is used to return the value
} of a constant.
static_eg(); Example

12
<?php Additionally, PHP supports user-defined or
define("Hello", "Welcome "); compound data types, specifically Arrays and
echo Hello; Objects. There are also special data types in PHP,
?> namely NULL and resource.
Output
Welcome
Difference between PHP Constants
and PHP Variables
PHP Constants PHP Variables
In PHP constants there is In PHP Variables the $
no need to use $ sign. sign is been used.
The data type of PHP The data type of the
constant cannot be PHP variable can be
changed during the changed during the This figure gives us a clear picture of PHP Data
execution of the script. execution of the script. types.
A PHP constant once A PHP variable can be Different Types of PHP Data Types
defined cannot be undefined as well as can
PHP has the following data types -
redefined. be redefined.
Under basic data types, we have -
We can not define a We can define a variable
• Integers
constant using any simple using a simple
assignment operator assignment • Floats (Floating-Point Numbers)
rather it can only be operation(=). • Strings
defined using define(). • Booleans
Usually, constants are On the other hand, • PHP Compound Data Types
written in numbers. variables are written in • Under compound data types, we have-
letters and symbols. • Arrays
PHP constants are PHP variables are not • Objects
automatically global automatically global in • PHP Special Data Types
across the entire script. the entire script.
• Under special data types, we have-
PHP constant is A PHP variable is
• Resource
comparatively slower comparatively faster
• NULL
than PHP variable than the PHP constant
PHP Integers
Exam Points Constants Can’t Be Changed Once
Defined: In PHP, integers are used to represent
• Once a constant is defined using define(), it whole numbers, including both positive and
cannot be changed or redefined during script negative values, without any fractional or decimal
execution. Unlike variables, constants are
part. They can be expressed in three bases:
immutable.
php decimal (base 10), octal (base 8), or hexadecimal
Copy code (base 16), with the default base being decimal.
define("SITE_NAME", "My Website");
• Decimal Integers:
• $decimal_integer = 42;
PHP Data Types • Octal Integers:
Variables in PHP are capable of storing $octal_integer = 052; // Leading 0 denotes
various types of data, each categorized into eight octal
distinct data types. These include basic, • Hexadecimal Integers:
compound, and special data types, each serving a
$hexadecimal_integer = 0x2A; // Leading 0x
specific purpose. You have basic data types like
Boolean, Integer, Double, and String. denotes hexadecimal

13
Example var_dump($decimal_float);
This example demonstrates the PHP integer type. echo "<br/>";
<?php var_dump($scientific_notation);
$decimal_integer = 42; ?>
$octal_integer = 052; Output:
$hexadecimal_integer = 0x2a; The first value is: 3.14
echo "The value of decimal_integer is: The second value is: 23000.
$decimal_integer<br/>"; float(3.14)
echo "The value of octal_integer is: float(23000)
$octal_integer<br/>";
PHP Strings
echo "The value of hexadecimal_integer is:
Strings store sequences of characters, including
$hexadecimal_integer<br/>";
letters and numbers. Use double quotes for
// Printing values and types
flexibility and single quotes for literal values.
var_dump($decimal_integer);
• Double-Quoted String:
echo "<br/>";
$double_quoted_string = "Hello, World!";
var_dump($octal_integer);
• Single-Quoted String:
echo "<br/>";
$single_quoted_string = 'PHP allows single-
var_dump($hexadecimal_integer);
quoted strings.';
?>
Output: Note: Understanding the difference between
The value of decimal_integer is: 42 single and double quotes is important, especially
The value of octal_integer is: 42 when dealing with variable values within strings.
The value of Hexa decimal_integer is: 42 Example
int(42)
This example demonstrates the PHP string data
int(42)
type.
int(42)
<?php
PHP Floats $str1 = 'Hello, world!';
In PHP, floats are versatile data types that $str2 = "Welcome at IncludeHelp";
can represent numbers with fractional or decimal echo "The first string is: $str1.<br/>";
parts, including both positive and negative values. echo "The second string is: $str2.<br/>";
They can also express numbers in exponential // Printing value, size, and type
form. var_dump($str1);
Decimal and Exponential Floats: echo "<br/>";
$decimal_float = 3.14; var_dump($str2);
$scientific_notation = 2.3e4; // 2.3 * 10^4 ?>
Output:
Example
The first string is: Hello, world!.
This example demonstrates the PHP float data
The second string is: Welcome at IncludeHelp.
type.
string(13) "Hello, world!"
<?php
string(22) "Welcome at IncludeHelp"
$decimal_float = 3.14;
$scientific_notation = 2.3e4; PHP Booleans
echo "The first value is: $decimal_float<br/>"; Booleans in PHP are fundamental for
echo "The second value is: conditional testing, holding either TRUE
$scientific_notation.<br/>"; (equivalent to 1) or FALSE (equivalent to 0).
// Printing value and type
14
Successful events typically return TRUE, while They are like containers for holding multiple pieces
unsuccessful events return FALSE. Additionally: of information. Here's an example with integers:
• NULL Values: $integer_array = [1, 2, 3, 4, 5];
$null_value = NULL; // Treated as FALSE in
Example
boolean
This example demonstrates the PHP array data
• Zero Values:
type.
$zero_value = 0; // Also considered FALSE in
<?php
boolean
$numbers = [1, 2, 3, 4, 5];
• Empty Strings:
echo "First element: $numbers[0]<br/>";
$empty_string = ''; // Treated as FALSE in
echo "Second element: $numbers[1]<br/>";
Boolean
echo "Third element: $numbers[2]<br/>";
Example echo "Fourth element: $numbers[3]<br/>";
This example demonstrates the PHP Boolean data echo "Fifth element: $numbers[4]<br/><br/>";
type. // Printing array's value and type
<?php var_dump($numbers);
$x = true; ?>
if ($x) { Output:
echo "It's true."; First element: 1
} else { Second element: 2
echo "It's false."; Third element: 3
} Fourth element: 4
echo "<br/>"; Fifth element: 5
$x = null; array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3)
if ($x) { [3]=> int(4) [4]=> int(5) }
echo "It's true.";
PHP Objects
} else {
Objects in PHP are instances of user-
echo "It's false.";
defined classes. They encapsulate both data and
}
functions specific to the class. Objects inherit
echo "<br/>";
properties and behaviors from the class, each
$x = "Hello";
instance having unique property values.
if ($x) {
echo "It's true."; Example
} else { <?php
echo "It's false."; class Car
} {
?> public $brand;
Output: public $model;
It's true. }
It's false. // Creating an instance of the Car class
It's true. $my_car = new Car();
$my_car->brand = "Toyota";
PHP Arrays
$my_car->model = "Camry";
Arrays, a compound data type in PHP,
echo $my_car->brand . "<br>";
efficiently store multiple values of the same data
echo $my_car->model;
type.
?>

15
Output: $float_variable = 3.14;
Toyota $string_variable = "Hello, PHP!";
Camry $boolean_variable = true;
$array_variable = [1, 2, 3];
In this example, we define a Car class with public
$object_variable = new stdClass();
properties $brand and $model. We then create an
$null_variable = null;
instance of the Car class named $my_car and set
echo "Integer: $integer_variable <br>";
its properties to specific values. After creating
echo "Float: $float_variable<br>";
the $my_car object, we demonstrate how to access
echo "String: $string_variable<br>";
its properties ($brand and $model) using the arrow
echo "Boolean: " . ($boolean_variable ? "true" :
(->) notation.
"false") . "<br>";
PHP NULL echo "Array: " . print_r($array_variable, true) .
NULL in PHP is a special variable type that "<br>";
can only hold one value: NULL. It is case-sensitive, echo "Object: " . print_r($object_variable, true) .
typically written in capital letters. When a variable "<br>";
is created without a value, or explicitly set to echo "NULL: " . var_export($null_variable, true) .
NULL, it automatically takes on this special value. "<br>";
Let's understand NULL by this example. ?>
Example Output:
<?php Integer: 42
$variable = null; Float: 3.14
echo "The variable is $variable <br>"; String: Hello, PHP!
Boolean: true
if (is_null($variable)) { Array: Array ( [0] => 1 [1] => 2 [2] => 3 )
echo "The variable is NULL"; Object: stdClass Object ( )
}
NULL: NULL
?>
This example demonstrates the use of
Output:
various PHP data types, including integers, floats,
The variable is
strings, booleans, arrays, objects and NULL.
The variable is NULL
In this example, we can see that the value Important Points on Variables and
of $variable is "NULL". It can be seen in the output Constants in PHP
that the first echo statement didn't display Variables in PHP
the $variable value. Dynamic Typing:
• PHP does not require explicit type declaration
PHP Resources
for variables. The type is determined by the
Resources in PHP are used to store
value assigned.
references, often to external functions or resources,
Naming Rules:
such as database connections. They are not an
• Variables must start with a dollar sign ($),
exact data type but serve as handles for specific
followed by a letter or an underscore. They can
operations like file handling or database
contain letters, numbers, and underscores.
connections.
Global Scope:
Example • Variables declared outside of functions have
<?php global scope. Inside functions, global variables
$integer_variable = 42;

16
must be accessed using the global keyword or Global Scope:
$GLOBALS. • Constants are automatically global and can be
Super global: accessed anywhere in the PHP script.
• PHP has built-in global arrays like $_GET, Case Sensitivity:
$_POST, $_SESSION, and others that are • By default, constants are case-insensitive, but
accessible across the script. this can be controlled by passing a third
Variable Variables: argument in the define() function.
• PHP allows the use of variable variables, where Magic Constants:
the name of a variable is stored in another • PHP has built-in magic constants like
variable. __LINE__, __FILE__, __DIR__, etc., which
References: provide contextual information about the
• Variables can be passed by reference using the script.
& symbol, allowing functions to modify the Constant Arrays:
original value. • PHP allows defining constants as arrays (since
Array Variables: PHP 5.6), enabling grouping of related
• PHP supports both indexed and associative constants.
arrays as variables to store multiple values. Built-in Constants:
Unset Variables: • PHP provides many built-in constants (e.g.,
• The unset() function is used to destroy a PHP_VERSION, E_ALL, PHP_OS) that give
variable, making it unavailable in the current information about the PHP environment.
scope. Class Constants:
Default Values: • Constants can be defined within classes using
• You can use the ternary operator to set default the const keyword, and can be accessed via
values for variables when they are not defined. ClassName::CONSTANT_NAME.
• Constants in PHP Difference from Variables:
Definition: • Constants cannot be modified once defined,
• Constants are defined using the define() unlike variables that can change values. They
function or the const keyword in classes. They are often used for values that should remain
cannot be changed after being set. unchanged throughout the script.

17
Practice Questions
1. What symbol is used to denote a variable in 11. Which of the following is NOT a scalar data
PHP? type in PHP?
A) % B) @ C) $ D) & A) Integer B) Float
2.Which of the following is a valid way to declare a C) Array D) String
variable in PHP? 12. What is the output of the following code?
A) var name = "John"; B) $name = "John"; $var = 10;
C) let name = "John"; D) define name = "John"; echo gettype($var);
3. What will be the output of the following code: A) Integer B) Float C) String D) Array
echo "Hello, $name"; if $name is set to "Alice"? 13. Which PHP data type is used to store
A) Hello, name B) Hello, Alice multiple values in a single variable?
C) Hello, $name D) Hello, "Alice" A) String B) Float
4. Which of the following types can a PHP C) Array D) Boolean
variable hold? 14. How does PHP treat a variable that has not
A) Only integers been initialized?
B) Only strings A) It automatically assigns it a value of 0.
C) Multiple data types, including arrays and objects B) It assigns it a NULL value.
D) Only booleans C) It throws an error.
5. What is the scope of a variable declared D) It assigns it a random value.
outside a function in PHP? 15. What will be the output of the following
A) Local B) Global code?
C) Static D) Private $var = "5";
6. What is the correct way to define a constant in $result = $var + 2;
PHP? echo $result;
A) const NAME = "Value"; A) 5 B) 7 C) 52 D) Error
B) define("NAME", "Value");
16. Which of the following is an example of an
C) constant NAME = "Value";
associative array in PHP?
D) variable NAME = "Value";
A) $colors = array("red", "green", "blue");
7. Which of the following statements about B) $ages = array("Alice" => 30, "Bob" => 25);
constants in PHP is true? C) $numbers = array(1, 2, 3);
A) Constants can change their value after being D) $data = array(10, "text", true);
defined.
17. What is the purpose of the isset() function in
B) Constants do not require a dollar sign ($).
PHP?
C) Constants can only hold integer values.
A) To check if a variable is defined and is not NULL.
D) Constants are case-insensitive by default.
B) To check if a variable is an array.
8. What will happen if you try to redefine a C) To retrieve the type of a variable.
constant in PHP? D) To count the number of elements in an array.
A) It will change the value of the constant.
18. Which of the following data types can
B) It will throw a fatal error.
represent both true and false values in PHP?
C) It will ignore the new value.
A) Integer B) String
D) It will redefine the constant with a warning.
C) Boolean D) Float
9. What is the output of the following code?
19. What will be the result of the following code?
define("SITE_NAME", "OpenAI");
$var = "Hello";
echo SITE_NAME;
$var .= " World!";
A) SITE_NAME B) OpenAI
echo $var;
C) "OpenAI" D) Error
A) Hello B) Hello World!
10. Which function is used to check if a constant C) HelloWorld! D) Error
is defined in PHP?
20. Which PHP function can be used to convert a
A) is_constant() B) check_constant()
string to an integer?
C) defined() D) constant_exists()
A) to_integer() B) intval()
C) str_to_int() D) cast_int()
Ans : 1-c,2-b,3-b,4-c,5-b,6-b,7-b,8-b,9-b,10-c,11-c,12-a,13-c,14-b,15-b,16-b,17-a,18-c,19-b,20-b

18
3. Operators and Expressions
PHP Operators
The following are the operators in PHP:
PHP operators are characters or sets of 1. Arithmetic Operators
characters used to manipulate or perform 2. Assignment Operators
operations on expressions and values. Operators 3. Comparison Operators
allow you to perform arithmetic operations, assign 4. Increment/Decrement Operators
values to variables, string concatenation, compare 5. Logical Operators
deals, and perform boolean operations. 6. String Operators
Operators are fundamental building blocks of 7. Array Operators
programming languages. They allow us to 8. Conditional Assignment Operators
manipulate and combine data to achieve desired PHP Arithmetic Operators
results. In PHP, there are many operators available Arithmetic operators are used to perform
for various purposes. This tutorial will introduce
basic mathematical operations like addition,
you to the most common PHP operators and
subtraction, multiplication, and division.
provide examples of their usage.
The following are the PHP arithmetic operators:

Operator Description Example


+ Addition $sum = 100 + 50; // $sum will be 150
- Subtraction $difference = 200 - 100; // $difference will be 100
* Multiplication $product = 5 * 3; // $product will be 15
/ Division $quotient = 100 / 2; // $quotient will be 50
% Modulus $remainder = 100 % 3; // $remainder will be 1

Example of PHP Arithmetic Operators echo $quotient . "<br>";


<?php echo $remainder . "<br>";
$sum = 100 + 50; ?>
$difference = 200 - 100; The output of the above example is:
$product = 5 * 3; 150
$quotient = 100 / 2; 100
$remainder = 100 % 3; 15
// printing 50
echo $sum . "<br>"; 1
echo $difference . "<br>";
echo $product . "<br>";
PHP Assignment Operators
Assignment operators are used to assign values to variables.
The following are the PHP assignment operators:
Operator Description Example
= Simple assignment $a = 65;
+= Adds and assigns $a += 5; means (a=a+5) // $a will be 70
-= Subtracts and assigns $a -= 5; means (a=a-5) // $a will be 65
*= Multiplies and assigns $a *= 2; means (a*2) // $a will be 130
/= Divides and assigns $a /= 2; // $a will be 10

19
Example of PHP Assignment Operators $a /= 2;
<?php echo $a . "<br>";
$a = 65; ?>
echo $a . "<br>"; The output of the above example is:
$a += 5; 65
echo $a . "<br>"; 70
$a -= 5; 65
echo $a . "<br>"; 130
$a *= 2; 65
echo $a . "<br>";
PHP Comparison Operators
Comparison operators are used to compare two values and return a Boolean (true/false) result.
The following are the PHP comparison operators:
Operator Description Example
== Equal to $a == 10; // true
!= Not equal to $a != 10; // false
< Less than $a < 10; // false
> Greater than $a > 10; // false
<= Less than or equal to $a <= 10; // true
>= Greater than or equal to $a >= 10; // true
<=> Spaceship operator (PHP 7+) $a <=> 10; // -1

Example of PHP Comparison Operators echo "<br>";


<?php
$result = $a >= 10;
$a = 10;
var_dump($result);
$result = $a == 10;
echo "<br>";
var_dump($result);
$result = $a <=> 10;
echo "<br>";
var_dump($result);
$result = $a != 10;
echo "<br>";
var_dump($result);
?>
echo "<br>";
The output of the above example is:
$result = $a < 10;
bool(true)
var_dump($result);
bool(false)
echo "<br>";
bool(false)
$result = $a > 10;
bool(false)
var_dump($result);
bool(true)
echo "<br>";
bool(true)
$result = $a <= 10;
int(0)
var_dump($result);
PHP Increment/Decrement Operators
Increment and decrement operators are used to increase or decrease the value of a variable by 1.
The following are the PHP increment/decrement operators:
Operator Description Example
++ Pre-increment ++$a; // $a becomes 11
-- Pre-decrement --$a; // $a becomes 9
$a++ Post-increment $a++; // $a becomes 10 (after the statement execution)
$a-- Post-decrement $a--; // $a becomes 9 (after the statement execution)
20
Example of PHP echo $a . "<br>";
Increment/Decrement Operators $a--;
<?php echo $a . "<br>";
$a = 10; ?>
++$a; The output of the above example is:
echo $a . "<br>"; 11
--$a; 10
echo $a . "<br>"; 11
$a++; 10

PHP Logical Operators


Logical operators are used to combine two or more Boolean values and return a single Boolean result.
The following are the PHP logical operators:
Operator Description Example
&& Logical And $a > 10 && $b < 5; // true only if both $a > 10 and $b < 5 are true
|| Logical Or $a and $b; // Return true if both are true
! Logical Not !($a > 10); // true if $a is not greater than 10
and Logical And $a and $b; // Return true if both are true
or Logical Or $a or $b; // Return true if either is true
xor Logical Xor $a xor $b; // Return true if either is true, but not both
Example of PHP Logical Operators echo "<br>";
<?php $result = ($a == 10 or $b == 5);
$a = 10; var_dump($result);
$b = 5; echo "<br>";
$result = $a == 10 && $b == 5; $result = ($a == 10 xor $b == 5);
var_dump($result); var_dump($result);
echo "<br>"; echo "<br>";
$result = $a == 10 || $b == 5; ?>
var_dump($result); The output of the above example is:
echo "<br>"; bool(true)
$result = !($a == 10 && $b == 5); bool(true)
var_dump($result); bool(false)
echo "<br>"; bool(true)
$result = ($a == 10 and $b == 5); bool(true)
var_dump($result); bool(false)

PHP String Operators


String operators are used to manipulate and combine strings.
The following are the PHP string operators:
Operator Description Example
. Concatenation $str1 = "Include" . " " . $str2;
.= String concatenation and assignment $str1 .= "Help";
== Equal to $str1 == "Include Help"; // true
!= Not equal to $str1 != "Include Help"; // false

21
Example of PHP String Operators echo "<br>";
<?php $result = $str1 != $str2;
$str1 = "Include"; var_dump($result);
$str2 = "Help"; echo "<br>";
$result = $str1 . $str2; ?>
echo $result . "<br>"; The output of the above example is:
$result .= $str1; IncludeHelp
echo $result . "<br>"; IncludeHelpInclude
$result = $str1 == $str2; bool(false)
var_dump($result); bool(true)
PHP Array Operators
Array operators in PHP are used to compare two arrays, these are basically a kind of relation operators
for the array companions.
The following are the PHP array operators:
Operator Description Example
+ Array Union $a + $b; - Returns union or arrays.
== Array Equality $a == $b; - Returns if both have the same key and value pairs.
=== Array Identity $a == $b; - Returns if both have the same key and value pairs (their
order and type must be same).
!= Array Inequality $a != $b; - Returns true if both are not equal.
<> Array Inequality $a <> $b; - Returns true if both are not equal.
!== Array non-identity $a <> $b; - Returns true if $a is not identical to $b.
Example of PHP Array Operators echo "<br>";
<?php var_dump($x !== $y);
$x = ["fruit" => "Apple", "color" => "Red"]; echo "<br>";
$y = ["company" => "Honda", "model" => "City"]; ?>
print_r($x + $y); The output of the above example is:
echo "<br>"; Array ( [fruit] => Apple [color] => Red [company]
var_dump($x == $y); => Honda [model] => City )
echo "<br>"; bool(false)
var_dump($x === $y); bool(false)
echo "<br>"; bool(true)
var_dump($x != $y); bool(true)
echo "<br>"; bool(true)
var_dump($x <> $y);
PHP Conditional Assignment Operators
Conditional assignment operators are used to define value based on the given conditions.
The following are the PHP conditional assignment operators:
Operator Description Example
?: Ternary Operator $result = expr1 ? expr2 : expr2;
?? Non-Coalescing Operator $result = expr1 ?? expr2;
Example of PHP Conditional // if $welcome either not defined or null
Assignment Operators $welcome = $welcome ?? "Hello, world!";
<?php echo "Welcome message is " . $welcome . "<br>";
$a = 10; ?>
$b = 5; The output of the above example is:
$result = $a > $b ? $a : $b; Largest value is 10
echo "Largest value is " . $result . "<br>"; Welcome message is Hello, world!
// Assigns "Hello, world!",

22
PHP Operators Practice (More return "Greater";
Examples) } else {
return "Smaller";
Exercise 1 }
Write a PHP script that calculates the area }
of a rectangle given its length and width using echo compareStrings("apple", "orange");
arithmetic operators. ?>
<?php The output of the above example is:
// Calculate the area of a rectangle Smaller
$length = 5;
$width = 8; Exercise 4
$area = $length * $width; Implement a PHP script that determines
echo "The area of the rectangle is: $area"; whether a given number is positive, negative, or
?> zero using the ternary operator.
The output of the above example is: <?php
The area of the rectangle is: 40 // Determine if a number is positive, negative, or
zero
Exercise 2 $number = -7;
Create a PHP script that checks if a given $result = $number > 0 ? "Positive" : ($number < 0
number is both divisible by 2 and 3. Use logical ? "Negative" : "Zero");
operators to perform the check. echo "The number is $result.";
<?php ?>
// Check if a number is divisible by 2 and 3 The output of the above example is:
$number = 12; The number is Negative.
if ($number % 2 == 0 && $number % 3 == 0) {
echo "$number is divisible by both 2 and 3."; Exercise 5
} else { Develop a PHP program that uses the
echo "$number is not divisible by both 2 and 3."; multiplication and assignment operator (*=) to
} calculate the square of a number.
?> <?php
The output of the above example is: // Calculate the square of a number using *=
12 is divisible by both 2 and 3. $number = 4;
$number *= $number;
Exercise 3 echo "The square of the number is: $number";
Write a PHP function that compares two ?>
strings and returns "Equal" if they are the same, The output of the above example is:
"Greater" if the first string is lexicographically
The square of the number is: 16
greater, and "Smaller" if the second string is
lexicographically greater. Exercise 6
<?php Write a PHP function that takes two numbers
// Compare two strings as parameters and uses the spaceship operator to
function compareStrings($str1, $str2) return:
{ • -1 if the first number is less than the second,
$result = strcmp($str1, $str2); • 0 if they are equal,
if ($result == 0) { • 1 if the first number is greater than the
return "Equal"; second.
} elseif ($result > 0) { <?php

23
// Use spaceship operator to compare two <?php
numbers // Concatenate two strings using .=
function compareNumbers($num1, $num2) function concatenateStrings($str1, $str2)
{ {
return $num1 <=> $num2; $str1 .= $str2;
} return $str1;
$result = compareNumbers(8, 5); }
echo "Result: $result"; echo concatenateStrings("Hello", " World!");
?> ?>
The output of the above example is: The output of the above example is:
Result: 1 Hello World!

Exercise 7
PHP Expressions
Create an array of fruits and another array
of vegetables. Use array operators to merge these An expression is a combination of values,
arrays and display the combined list. variables, operators, and function calls that can be
<?php evaluated to produce a value.
// Merge arrays of fruits and vegetables In PHP, an expression is a combination of
$fruits = ["apple", "banana", "orange"]; values, variables, operators, and function calls that
$vegetables = ["carrot", "broccoli", "spinach"]; can be evaluated to produce a single value. These
$combined = $fruits + $vegetables; elements come together to form a logical
print_r($combined); operation, and the result of this operation is the
?> output of the expression.
The output of the above example is:
Array ( [0] => apple [1] => banana [2] => orange ) Components of an Expression:
• Values: These are the raw data elements in
Exercise 8 programming. Examples include numbers (3,
Implement a PHP script that uses a loop to 10.2), strings (‘Hello World'), and
print the numbers from 1 to 10 using the post- booleans (true, false).
increment operator. • Variables: Variables are containers for holding
<?php values. They have names and can store
// Print numbers from 1 to 10 using post- different values at different points in program’s
increment operator execution.
$i = 1; • Operators: Operators are symbols or keywords
while ($i <= 10) { that perform operations on values and
echo "$i "; variables. Examples include arithmetic
$i++; operators (+, -, * /), comparison operators (==,
} !=, <, >) and logical operators (&&, || ).
?> • Function Calls: Functions are reusable blocks
The output of the above example is: of code that perform specific tasks. When you
1 2 3 4 5 6 7 8 9 10 call a function, it can return a value. Function
Exercise 9 calls typically involve passing arguments
enclosed in parentheses. Visit
Write a PHP function that takes two strings
@pr0fess0racademy.com
as parameters and concatenates them using the
concatenation and assignment operator (.=).
Return the resulting string.

24
Exam Points $a >= $b; // greater than or equal to
PHP expressions are evaluated based on the $a == $b; // equal
precedence and associativity of the operators $a != $b; // not equal
involved. PHP follows a standard set of rules to $a < $b; // less than
determine which operations to perform first. For
$a <= $b; // less than or equal to
example, multiplication has a higher precedence
than addition. $a === $b; // identical (equal and same type)
$a !== $b; // not identical (not equal or not same
$result = 5 + 3 * 2; // Outputs 11, not 16, because
type)
multiplication is done first
Ternary Operator Expression:
Examples of Expressions
$number = 7;
Basic Expressions $isEven = ($number % 2 == 0) ? true : false;
The simplest forms of expressions are constants The expression uses the ternary operator to
and variables. determine if. $number is even,
For example: producing true or false accordingly.
$a = 5; // 5 is an expression with the value 5
$b = $a; // $a is an expression with the value 5 Increment and Decrement Operators
Functions are also expressions. For instance: PHP supports pre-increment (++$variable)
and post-increment ($variable++) operators. The
function foo() {
difference lies in the value of the increment
return 5;
expression: These operators are called increment
} and decrement operators respectively. They are
$c = foo(); // foo() is an expression with the value unary operators, needing just one operand and can
5 be used in prefix or postfix manner, although with
PHP supports four scalar value types: int, float, different effect on value of expression.
string, and bool. It also supports two composite Both prefix and postfix ++ operators
types: arrays and objects increment value of operand by 1 (whereas --
operator decrements by 1). However, when used in
Arithmetic Expression: assignment expression, prefix makes
$result = 5 + 3; increment/decrement first and then followed by
Here, the expression 5+3 adds the values 5and 3, assignment. In case of postfix, assignment is done
resulting in the value 8. before increment/decrement
Uses postfix ++ operator
String Concatenation Expression: Example
$name = 'John'; <?php
$greetings = 'Hello', . $name; $x=10;
The expression "Hello, " . $name concatenates the $y=$x++; //equivalent to $y=$x followed by
string "Hello, " with the value store in the $x=$x+1
variable $name . echo "x = $x y = $y";
Function Call Expression: ?>
$length = strlen('Hello'); Output
The expression calls the strlen function to get the This produces following result
length of the string 'Hello' , producing the value 5 . x = 11 y = 10
Whereas following example uses prefix increment
Comparison Expression: operator in assignment
Comparison expressions evaluate to either true or Example
false. PHP supports various comparison operators: <?php
$a > $b; // greater than $x=10;

25
$y=++$x;; //equivalent to $x=$x+1 followed by Assignment Expressions
$y=$x Assignments in PHP are expressions that evaluate
echo "x = $x y = $y"; to the assigned value. For example:
?> $a = 5; // $a = 5 is an expression with the value 5
Output $b = ($a = 5); // $b = $a = 5 is like writing $a = 5;
x = 11 y = 11 $b = 5;
Pre-increment increments the variable before Assignments are parsed from right to left, so you
reading its value, while post-increment increments can write:
1the variable after reading its value1. $b = $a = 5;

Practice Questions
1. What will the following PHP expression A) true B) false
output? echo 5 + 10 * 2; C) null D) undefined
A) 15 B) 25 C) 20 D) 10
11. What will the expression !(true || false)
2.Which operator is used for string evaluate to?
concatenation in PHP? A) true B) false C) null D) 1
A) . B) + C) & D) *
12. Which operator is used to check if a variable
3. What will the value of $x be after executing $x is not set or is null?
= 5; $x += 10;? A) isset() B) empty() C) ! D) ??
A) 15 B) 10 C) 5 D) 0
13. What will the result of the expression 5 ** 2
4. What is the result of the following expression: be in PHP?
true && false? A) 10 B) 25 C) 2.5 D) 5
A) true B) false C) null D) 1
14. If $a = 5; $b = 3; what will $a <=> $b
5. Which of the following will compare two evaluate to?
values for equality without type conversion? A) -1 B) 0 C) 1 D) null
A) == B) === C) != D) !==
15. What will the output of echo 10 == "10"; be?
6. What does the ?? operator do in PHP? A) true B) false C) 1 D) Error
A) Returns the first operand if it's true
16. Which of the following operators is not a
B) Returns the first non-null operand
bitwise operator?
C) Concatenates two strings
A) & B) | C) ^ D) &&
D) Compares two values
17. What will the following code output?
7. What will the output of the following code be?
$x = 10;
php
$y = 20;
$a = 1;
$result = $x < $y ? 'Less' : 'Greater';
$b = '1';
echo $result;
if ($a == $B) {
A) Less B) Greater
echo "Equal";
C) Error D) 10
} else {
echo "Not Equal"; 18. What is the outcome of array(1, 2, 3) +
} array(4, 5, 6)?
A) Equal B) Not Equal A) array(1, 2, 3, 4, 5, 6)
C) Error D) Undefined B) array(1, 2, 3)
C) Error
8. Which operator would you use to increment a
D) array(0 => 1, 1 => 2, 2 => 3)
variable by one?
A) ++ B) +1 C) +=1 D) -- 19. Which of the following is the correct way to
concatenate two strings in PHP?
9. In PHP, what is the result of 10 % 3?
A) $str1 & $str2 B) $str1 + $str2
A) 3 B) 1 C) 0 D) 10
C) $str1 . $str2 D) $str1 * $str2
10. What will isset($var) return if $var is not
20. What will the result of 5 == '5' be in PHP?
defined?
A) true B) false C) 1 D) 0
Ans : 1-b,2-a,3-a,4-b,5-b,6-b,7-a,8-a,9-b,10-b,11-b,12-d,13-b,14-c,15-a,16-d,17-a,18-b,19-c,20-a

26
4. Control Structures in PHP
Introduction In the above example, the program checks
In simple terms, a control structure allows whether or not the user is logged in. Based on the
you to control the flow of code execution in your user's login status, they will be redirected to either
application. Generally, a program is executed the Login page or the My Account page. In this
sequentially, line by line, and a control structure case, a control structure ends code execution by
allows you to alter that flow, usually depending on redirecting users to a different page. This is a
certain conditions. crucial ability of the PHP language.

Control structures are core features of the


Different types of control
PHP language that allow your script to respond
structures:
differently to different inputs or situations. This
could allow your script to give different responses PHP supports a number of different control
based on user input, file contents, or some other structures:
data. • if
The following flowchart explains how a • else
control structure works in PHP. • elseif
• switch
• while
• do-while
• for
• foreach and more

PHP If Statement
The if construct allows you to execute a
piece of code if the expression provided along with
it evaluates to true.

First a condition is checked. If the condition is true,


the conditional code will be executed. The
important thing to note here is that code execution
continues normally after conditional code
execution.
Let's consider the following example

Syntax
The syntax for if… then… else is;
<?php
if (condition is true) {
block one
else
block two
}

27
?> if ($age < 30)
Let's have a look at the following example to {
understand how it actually works. echo "Your age is less than 30!";
The code below uses “if… then… else” to }
determine the larger value between two numbers. else
<?php {
echo "Your age is greater than or equal to 30!";
$first_number = 7;
}
$second_number = 21;
?>
if ($first_number > $second_number){
Output:
echo "$first_number is greater than
Your age is greater than or equal to 30!
$second_number";
}else{ So when you have two choices, and one of them
echo "$second_number is greater than must be executed, you can use the if-else
$first_number"; construct.
} PHP Else If Statement
?> We can consider the elseif statement as an
Output: extension to the if-else construct. If you've got
21 is greater than 7 more than two choices to choose from, you can use
the elseif statement.
PHP Else Statement
Let's study the basic structure of the elseif
In the previous section, we discussed the if
statement, as shown in the following pseudo-code.
construct, which allows you to execute a piece of
if (expression1)
code if the expression evaluates to true. On the
{
other hand, if the expression evaluates to false, it
// code is executed if the expression1 evaluates
won't do anything. More often than not, you also
to TRUE
want to execute a different code snippet if the
}
expression evaluates to false. That's where the else
elseif (expression2)
statement comes into the picture.
{
You always use the else statement in // code is executed if the expression2 evaluates
conjunction with an if statement. Basically, you can to TRUE
define it as shown in the following pseudo-code. }
if (expression) elseif (expression3)
{ {
// code is executed if the expression evaluates to // code is executed if the expression3 evaluates
TRUE to TRUE
} }
else else
{ {
// code is executed if the expression evaluates to // code is executed if the expression1,
FALSE expression2 and expression3 evaluates to FALSE,
} a default choice
}
Let's revise the previous example to Again, let's try to understand it using a real-
understand how it works. world example.
<?php <?php
$age = 50;
28
$age = 50; Exam Points
if ($age < 30) The break statement is used inside switch (and
{ other loops) to terminate the loop or switch case
echo "Your age is less than 30!"; early. Without break, the program will continue
} checking the subsequent cases, which may not be
elseif ($age > 30 && $age < 40) desirable.
{
echo "Your age is between 30 and 40!"; As usual, an example is the best way to understand
} the switch statement.
elseif ($age > 40 && $age < 50) <?php
{
$favourite_site = 'Code';
echo "Your age is between 40 and 50!";
} switch ($favourite_site) {
else case 'Business':
{ echo "My favourite site is
echo "Your age is greater than 50!"; business.tutsplus.com!";
} break;
?> case 'Code':
Output
echo "My favourite site is code.tutsplus.com!";
Your age is greater than 50!
break;
As you can see in the above example, we
case 'Web Design':
have multiple conditions, so we've used a series of
echo "My favourite site is
elseif statements. In the event that all if conditions
evaluate to false, it executes the code provided in webdesign.tutsplus.com!";
the last else statement. break;
case 'Music':
PHP Switch Statement
echo "My favourite site is music.tutsplus.com!";
The switch statement is somewhat similar
to the elseif statement which we've just discussed break;
in the previous section. The only difference is the case 'Photography':
expression which is being checked. echo "My favourite site is
In the case of the elseif statement, you have photography.tutsplus.com!";
a set of different conditions, and an appropriate break;
action will be executed based on a condition. On default:
the other hand, if you want to compare a variable echo "I like everything at tutsplus.com!";
with different values, you can use the switch }
statement.
?>
As you can see in the above example, we
want to check the value of the $favourite_site
variable, and based on the value of the
$favourite_site variable, we want to print a
message.
For each value you want to check with the
$favourite_site variable, you have to define the case
block. If the value is matched with a case, the code
associated with that case block will be executed.
After that, you need to use the break statement to
end code execution.

29
If you don't use the break statement, script }
execution will be continued up to the last block in Let's have a look at a real-world example to
the switch statement. understand how the while loop works in PHP.
<?php
Finally, if you want to execute a piece of
$max = 0;
code if the variable's value doesn't match any case,
echo $i = 0;
you can define it under the default block. Of
echo ",";
course, it's not mandatory—it's just a way to
echo $j = 1;
provide a default case.
echo ",";
So that's the story of conditional control $result=0;
structures. We'll discuss loops in PHP in the next while ($max < 10 )
section. {
Loops in PHP $result = $i + $j;
$i = $j;
Loops in PHP are useful when you want to
$j = $result;
execute a piece of code repeatedly until a
$max = $max + 1;
condition evaluates to false. So code is executed
echo $result;
repeatedly as long as a condition evaluates to true,
echo ",";
and as soon as the condition evaluates to false, the
}
script continues executing the code after the loop.
?>
Output
0,1,1,2,3,5,8,13,21,34,55,89,
If you're familiar with the Fibonacci series, you
might recognize what the above program does—it
outputs the Fibonacci series for the first ten
numbers. The while loop is generally used when
While Loop in PHP you don't know the number of iterations that are
The while loop is used when you want to execute a
going to take place in a loop.
piece of code repeatedly until the while condition
evaluates to false. Do-While Loop in PHP
The do-while loop is very similar to the while
loop, with the only difference being that the while
condition is checked at the end of the first iteration.
Thus, we can guarantee that the loop code is
executed at least once, irrespective of the result of
the while expression.

You can define it as shown in the following


pseudo-code.
while (expression)
{
// code to execute as long as expression
evaluates to TRUE
30
syntax of the do-while loop. After execution of the loop code, the expr3 is
executed. Generally, the expr3 is used to alter the
do
value of a variable which is used in the expr2
{
expression.
// code to execute
} while (expression); Let's go through the following example to see
how it works.
Let's go through a real-world to understand
<?php
possible cases where you can use the do-
for ($i=1; $i<=10; ++$i)
while loop.
{
<?php
echo sprintf("The square of %d is %d.</br>", $i,
$handle = fopen("file.txt", "r");
$i*$i);
if ($handle)
}
{
?>
do
The above program outputs the square of the first
{
ten numbers. It initializes $i to 1, repeats as long as
$line = fgets($handle);
$i is less than or equal to 10, and adds 1 to $i at
// process the line content
each iteration.
} while($line !== false);
} For Each in PHP
fclose($handle); The foreach loop is used to iterate over array
?> variables. If you have an array variable, and you
In the above example, we're trying to read a file want to go through each element of that array, the
line by line. Firstly, we've opened a file for reading. foreach loop is the best choice.
In our case, we're not sure if the file contains any Let's have a look at a couple of examples.
content at all. Thus, we need to execute the fgets <?php
function at least once to check if a file contains any $fruits = array('apple', 'banana', 'orange', 'grapes');
content. So we can use the do-while loop here. do- foreach ($fruits as $fruit)
while evaluates the condition after the first iteration {
of the loop. echo $fruit;
For Loop in PHP echo "<br/>";
}
Generally, the for loop is used to execute a
$employee = array('name' => 'John Smith', 'age'
piece of code a specific number of times. In other
=> 30, 'profession' => 'Software Engineer');
words, if you already know the number of times
foreach ($employee as $key => $value)
you want to execute a block of code, it's the for loop
{
which is the best choice.
echo sprintf("%s: %s</br>", $key, $value);
Let's have a look at the syntax of the for loop echo "<br/>";
for (expr1; expr2; expr3) }
{ ?>
// code to execute If you want to access array values, you can use the
} first version of the foreach loop, as shown in the
The expr1 expression is used to initialize variables, above example. On the other hand, if you want to
and it's always executed. The expr2 expression is access both a key and a value, you can do it as
also executed at the beginning of a loop, and if it shown in the $employee example above.
evaluates to true, the loop code is executed.

31
Breaking Out of the Loop current loop iteration instead of breaking out of the
There are times when you might want to loop altogether. Just like break, you can also use a
break out of a loop before it runs its course. This numerical value with continue to specify how many
can be achieved easily using the break keyword. It nested loops it should skip for the current iteration.
will get you out of the current for, foreach, while, <?php
do-while, or switch structure. echo 'Simple Continue';
for($i = 1; $i <= 2; $i++) {
You can also use break to get out of multiple
echo "\n".'$i = '.$i.' ';
nested loops by supplying a numeric argument. For
for($j = 1; $j <= 5; $j++) {
example, using break 3 will break you out of 3
if($j == 2) {
nested loops. However, you cannot pass a variable
continue;
as the numeric argument if you are using a PHP
}
version greater than or equal to 5.4
echo '$j = '.$j.' ';
<?php }
echo "Simple Break\n"; }
for($i = 1; $i <= 2; $i++) { /*
echo "$i = $i "; Simple Continue
for($j = 1; $j <= 5; $j++) { i=1j=1j=3j=4j=5
if($j == 2) { i=2j=1j=3j=4j=5
break; */
} echo 'Multi-level Continue';
echo "$j = $j "; for($i = 1; $i <= 2; $i++) {
} echo "\n".'$i = '.$i.' ';
echo "\n"; for($j = 1; $j <= 5; $j++) {
} if($j == 2) {
continue 2;
echo "Multi-level Break\n";
}
for($i = 1; $i <= 2; $i++) {
echo '$j = '.$j.' ';
echo "$i = $i ";
}
for($j = 1; $j <= 5; $j++) {
}
if($j == 2) {
/*
break 2;
Multi-level Continue
}
i=1j=1
echo "$j = $j ";
i=2j=1
}
*/
echo "\n";
?>
}
Output Exam Points
The goto statement in PHP allows you to jump to
Simple Break
another part of the program. It’s often discouraged,
1=11=1 as it can lead to code that’s difficult to understand
2=22=1 and maintain, but it can be useful in specific cases.
<php>
goto mylabel;
Multi-level Break
echo "This will be skipped.";
1=11=1 mylabel:
echo "This will be executed.";
<?php>
Another keyword that can interrupt loops in PHP
is continue. However, this only skips the rest of the
32
PHP Mixing Decisions and looping with Html
Combining of decisions (if statement) and looping (foreach loop) in PHP within an HTML
document. In this example, we'll use PHP to list of even and odd numbers based on user input:

Here's a simple example that demonstrates the use <input type="number" name="userInput"
of decisions (if statement) and looping (for loop) id="userInput" required>
within an HTML document: <input type="submit" value="Generate
Code: Numbers">
<!DOCTYPE html> </form>
<html lang="en"> <?php
<head> // Check if the form is submitted
<meta charset="UTF-8"> if ($_SERVER["REQUEST_METHOD"] ==
<meta name="viewport" "POST") {
content="width=device-width, initial-scale=1.0"> // Get user input
<title>PHP Decision and Looping $userInput = $_POST["userInput"];
Example</title>
// Validate input to ensure it's a positive integer
</head>
if (is_numeric($userInput) && $userInput > 0 &&
<body>
$userInput == round($userInput)) {
<h1>PHP Decision and Looping
echo "<h2>Generated Numbers:</h2>";
Example</h1>
// Looping: foreach loop to generate even and
<form action="" method="post">
odd numbers
<label for="userInput">Enter a
echo "<p>Even Numbers: ";
number:</label>
for ($i = 0; $i <= $userInput; $i += 2) {

33
echo "$i "; </body>
} </html>
echo "</p>"; Output:
In this example:
echo "<p>Odd Numbers: ";
1. The user is prompted to enter a number.
for ($i = 1; $i <= $userInput; $i += 2) {
2. When the form is submitted, PHP checks if
echo "$i ";
the input is a positive integer.
}
3. If the input is valid, PHP uses a foreach loop
echo "</p>";
to generate and display even and odd
} else {
numbers up to the user's input.
// Display an error message for invalid input
4. If the input is invalid, an error message is
echo "<p style='color: red;'>Please enter a valid
displayed in red.
positive integer.</p>";
This example showcases how PHP can be used for
}
decision-making (checking user input) and looping
}
(generating and displaying numbers) within an
?>
HTML document.

Practice Questions
1. Which of the following is the correct syntax 6. What will the output of the following code be?
for a conditional statement in PHP? $day = 3;
A) if condition { } B) if (condition) { }
C) if condition: D) if [condition] { } switch ($day) {
case 1:
2.What will the following code output? echo "Monday";
$x = 10; break;
if ($x > 5) { case 2:
echo "Greater"; echo "Tuesday";
} else { break;
echo "Smaller"; case 3:
} echo "Wednesday";
A) Greater B) Smaller break;
C) 10 D) Error default:
3. Which control structure is used to execute a echo "Not a valid day";
block of code multiple times? }
A) if B) switch C) for D) echo A) Monday B) Tuesday
C) Wednesday D) Not a valid day
4. What is the purpose of the break statement in
PHP? 7. In a for loop, which part is executed only
A) To exit a function once?
B) To terminate a loop or switch A) Initialization B) Condition
C) To stop the script execution C) Increment/Decrement D) Body of the loop
D) To continue to the next iteration
5. Which of the following is the correct syntax 8. What does the continue statement do in a
for a switch statement? loop?
A) switch (expression) { case x: } A) Exits the loop
B) switch expression { case x: } B) Stops the current iteration and continues to the next
C) switch { case x: expression } C) Restarts the loop
D) switch (expression) case x: D) Skips the next iteration

34
9. How many times will the following code block
15. Which loop will always execute at least
execute?
once?
for ($i = 0; $i < 5; $i++) {
A) for B) while
echo $i;
C) do...while D) foreach
}
A) 4 B) 5 C) 6 D) 0 16. What will the following code output?
$day = "Saturday";
10. Which of the following correctly defines a if ($day == "Saturday" || $day == "Sunday") {
while loop? echo "Weekend";
A) while (condition) { } B) while condition { } } else {
C) while { condition } D) while: condition { } echo "Weekday";
}
11. Which of the following is the correct syntax
A) Weekend B) Weekday
for a foreach loop?
C) Saturday D) Error
A) foreach (array as value) { }
17. How do you define a multi-line comment in
B) foreach array as value { }
PHP?
C) foreach (array as value) { }
A) // This is a comment
D) foreach (value in array) { }
B) /* This is a comment */
12. What will the following code output? C) # This is a comment
$i = 0; D) <!-- This is a comment -->
while ($i < 3) {
18. What does the switch statement evaluate?
echo $i;
A) A single condition
$i++;
B) Multiple conditions simultaneously
}
C) An expression
A) 012 B) 123 C) 321 D) 00
D) A function
13. What is the purpose of the else if statement?
A) To execute a block of code if the first condition is 19. In a do...while loop, when is the condition
false checked?
B) To create a loop A) Before executing the loop
C) To exit from a switch statement B) After executing the loop
D) To initialize a variable C) During the loop
D) Never checked
14. What will the result of the following code be?
$x = 10; 20. What will be the output of the following
if ($x == 10) { code?
echo "Ten"; $x = 5;
} elseif ($x == 20) { if ($x < 10) {
echo "Twenty"; echo "Less than 10";
} else { } else {
echo "Not Ten or Twenty"; echo "10 or more";
} }
A) Ten B) Twenty A) Less than 10 B) 10 or more
C) Not Ten or Twenty
b,20-a D) Error C) 5 D) Error
Ans : 1-b,2-a,3-c,4-b,5-a,6-c,7-a,8-b,9-b,10-a,11-a&c,12-a,13-a,14-a,15-c,16-a,17-b,18-c,19-

"The secret to getting ahead is getting started." – Mark Twain

35

You might also like