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

PHP & MYSQL Unit-1

Uploaded by

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

PHP & MYSQL Unit-1

Uploaded by

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

Course Title: DSC (17) PHP & MYSQL

PHP & MYSQL LAB


Course Code:235630

Unit-1 Introduction to PHP: Introduction to PHP, History and Features of PHP,


Installation & Configuration of PHP, Embedding PHP code in Your Web Pages,
Understanding PHP, HTML and White Space, Writing Comments in PHP,
Sending Data to the Web Browser, Datatypes in PHP, Key words in PHP, Using
Variables, Constants in PHP, Expressions in PHP, Operators in PHP.
Programming with PHP: Conditional statements: if, if-else, switch, The
‘?’Operator, Looping statements: while Loop, do-while Loop, for Loop.

Unit-3 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.
Strings in PHP: What is String? Creating and Declaring String, String
Functions, Application program on sending Email.
Form Handling: Creating HTML Form, Handling HTML Form data in PHP.

Unit-4 Database Handling Using PHP with MySQL: Introduction to MySQL:


Database terms, Data Types.
Accessing MySQL –Using MySQL Client and Using php My Admin,
MySQL Commands, Using PHP with MySQL: PHP MySQL Functions,
connecting to MySQL and Selecting the
Database,ExecutingSimpleQueries,RetrievingQueryResults,CountingReturned
Records,UpdatingRecordswithPHP.
Unit-1

PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially,
PHP was supposed to be an abbreviation for "Personal Home Page", but it now stands for the
recursive initialism "PHP: Hypertext Preprocessor".
Today, PHP is the world’s most popular server-side programming language for building web
applications. Over the years, it has gone through successive revisions and versions.

PHP - History
PHP started out as a small open-source project that evolved gradually as more and more people
found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994.
At that time, PHP stood for Personal Home Page, as he used it to maintain his personal
homepage. Later on, he added database support and called it as "Personal Home Page/Forms
Interpreter" or PHP/FI, which could be used to build simple, dynamic web applications.

​ Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP
3. The name of the language was also changed to the recursive acronym PHP: Hypertext
Preprocessor. They are also the authors of Zend Engine, a compiler and runtime
environment for the PHP. Zend Engine powered PHP 4 was released in May 2000.
​ PHP 5 was released in 2004, which included many new features such as OOP support,
the PHP Data Objects (PDO), and numerous performance enhancements.
​ PHP 7, is a new major PHP version which was developed in 2015. It included new
language features, most notable being, the introduction of return type declarations for
functions which complement the existing parameter type declarations, and support for the
scalar types (integer, float, string, and boolean) in parameter and return type declarations.

Features of PHP
Simplicity

● PHP is known for its simplicity and ease of learning.


● Organized and user-friendly syntax appeals to beginners.
● Abundance of pre-defined functions simplifies programming tasks.
● No need for extensive libraries like in languages such as C.

Flexibility

● PHP scripts run seamlessly on various devices, including mobile, tablet, and PC.
● Can be embedded into HTML, XML, and JavaScript.
● Compatible with multiple databases, enhancing data manipulation options.
● Works efficiently with major web servers like Apache and IIS.
Object-Oriented Programming (OOP)

● PHP supports OOP principles like inheritance, encapsulation, and abstraction.


● Object-oriented features introduced in PHP5.
● Enables creation of reusable and modular code, similar to Java and Python.

Interpreted Language

● PHP is interpreted, eliminating the need for compilation.


● Interpreters execute code line by line, promoting platform independence.
● Supports dynamic typing, allowing more flexibility in coding.
● Results in smaller executable program sizes compared to compiled languages.

Efficiency

● Efficient memory management and session handling.


● Minimizes unnecessary memory allocation.
● Contributes to smoother application performance.

Fast Performance

● PHP scripts generally load web pages faster.


● Execution within its memory space enhances speed.
● Efficient database connectivity further contributes to performance.

Open-Source and Free

● PHP is open-source and freely available.


● No licensing costs, making it cost-effective.

Case-Sensitivity

● PHP is partially case-sensitive.


● Variable names, constructs (if, while), keywords, functions, and class names are
case-sensitive.

Loosely Typed Language

● PHP supports variable declaration without specifying data types.


● Enhances coding flexibility and ease.

Server-Side Scripting

● Primarily used for server-side scripting.


● Generates dynamic content on web pages.
Extensibility

● PHP can be extended with custom extensions written in C.


● Offers flexibility to incorporate low-level functionality into PHP applications.

PHP Versions
PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He
called this suite of scripts "Personal Home Page Tools". It can be regarded as PHP version 1.0.

​ In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL,
and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the
version 2.0 status.
​ PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi
Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a
mature interface for multiple databases, protocols and APIs, object-oriented
programming support, and consistent language syntax.
​ PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many
web servers, HTTP sessions, output buffering, secure ways of handling user input and
several new language constructs.
​ PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0
with a new object model and dozens of other new features. PHP's development team
includes dozens of developers and others working on PHP-related and supporting
projects such as PEAR, PECL, and documentation.
​ PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation
(phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the
important features of PHP 7 include its improved performance, reduced memory usage,
Return and Scalar Type Declarations and Anonymous Classes.
​ PHP 8.0 was released on 26 November 2020. This is a major version having many
significant improvements from its previous versions. One standout feature is Just-in-time
compilation (JIT) that can provide substantial performance improvements. The latest
version of PHP is 8.2.8, released on July 4th, 2023.

Installation & Configuration of PHP


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:

○ WAMP for Windows

○ LAMP for Linux

○ MAMP for Mac


○ SAMP for Solaris

○ FAMP for FreeBSD

○ 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.

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.
Step 5: Click Next and move ahead.
Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.
Step 7: A finish window will display after successful installation. Click on the Finish button.

Step 8: Choose your preferred language.

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.

Embedding PHP code in Your Web Pages

PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal
Home Page.
We can use PHP in HTML code by simply adding a PHP tag without doing any extra work.
Example 1: First open the file in any editor and then write HTML code according to requirement.
If we have to add PHP code then we can add by simply adding <?php ….. ?> tags in between
and add your PHP code accordingly.
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<h1>
<?php
echo "Hii Hello PHP "
?>
</h1>
</body>
</html>

Understanding PHP
● Php runs on different OS like windows, unix and linux and support different Database
like mysql, ms access and oracle.
● Php can not only collect form data but it can also create, read, write, delete and close
files on the server.

EXAMPLE:

<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>

</html>

HTML and White Space

Writing comments in PHP

There are two ways in which you can add comments to your PHP code. The first turns a single
line into a comment by preceding it with a pair of forward slashes:
// This is a comment
This version of the comment feature is a great way to temporarily remove a line of code from
a program that is giving you errors.
For example, you could use such a comment to hide a debugging line of code until you need it,
like this:
// echo "X equals $x";
You can also use this type of comment directly after a line of code to describe its action, like
this:
$x += 10; // Increment $x by 10
When you need multiple-line comments, there’s a second type of comment, which looks like
Example 3-2.
Example 3-2. A multiline comment

You can use the /* and */ pairs of characters to open and close comments almost anywhere
you like inside your code. Most, if not all, programmers use this construct to temporarily
comment out entire sections of code that do not work or that, for one reason or another, they
do not wish to be interpreted.

A common error is to use /* and */ to comment out a large section of code that already
contains a commented-out section that uses those characters. You can’t nest comments this
way; the PHP inter‐ preter won’t know where a comment ends and will display an error
message. However, if you use a program editor or IDE with syntax highlighting, this type of
error is easier to spot.

Sending data to the web browser


● To create a dynamic website in php you must know how to send te data to the web
browser
● Php has number of built-in functions for this purpose the most common being used is
‘echo’ and ‘print’

Echo “hello world”;


Print “hello world”;

You could use print instead if u prefer,


● The first quotation mark after the function name indicates the start of the message to be
printed
● The next quotation mark indicate the end of the message to be printed.

EXAMPLE:

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>

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

</body>
</html>

OUTPUT:

My first PHP page


Hello World!
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:

1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>

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.

Rules for integer:


○ An integer can be either positive or negative.

○ An integer must not contain decimal point.

○ Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).

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

1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>

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:

1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>

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:

Example:

1. <?php
2. $college = "Mahajana";
3. //both single and double quote statements will treat different
4. echo "Hello $college";
5. echo "</br>";
6. echo 'Hello $college';
7. ?>

Output:

Hello Mahajana
Hello $college

PHP Array

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

Example:

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

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

PHP object

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

Example:

1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>

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:

1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>

Output:

Key words in PHP,

PHP keywords are predefined, reserved words in PHP that are used to perform specific
functions. These keywords are reserved by PHP and cannot be used as variable names,
function names, or class names. PHP keywords are case-insensitive, meaning that they can be
written in either upper or lower case letters.

Here is a list of PHP keywords:


abstract and array as break callable case catch class clone const
continue declare default die do echo else elseif empty end declare end for
end for each end if endswitch endwhile extends final finally for foreach function global
goto if implements include include_once instanceof instead of interface Is set list
namespace new or print private protected public require require_once return static
switch throw trait try unset use var while xor yield __halt_compiler

Using Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:

○ As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.

○ After declaring a variable, it can be reused throughout the code.

○ Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;

Rules for declaring PHP variable:

○ A variable must start with a dollar ($) sign, followed by the variable name.

○ It can only contain alpha-numeric character and underscore (A-z, 0-9, _).

○ A variable name must start with a letter or underscore (_) character.

○ A PHP variable name cannot contain spaces.

○ One thing to be kept in mind that the variable name cannot start with a number or special
symbols.

○ PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.

PHP Variable: Declaring string, integer, and float

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

File: variable1.php

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

Output:

string is: hello string


integer is: 200
float is: 44.6

Constants in PHP,
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.

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax
of define() function in PHP.

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().

1. <?php
2. define("MESSAGE","Hello PHP");
3. echo MESSAGE;
4. ?>
Hello PHP

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.

1. <?php
2. const MESSAGE="Hello const by PHP";
3. echo MESSAGE;
4. ?>

Hello const by PHP

Note: Unlike variables, constants are automatically global throughout the script.

Expressions in PHP,

Expressions are the most important building blocks of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".

The most basic forms of expressions are constants and variables. When you type $a = 5, you're
assigning 5 into $a. 5, obviously, has the value 5, or in other words 5 is an expression with the
value of 5 (in this case, 5 is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd
expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value
of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the
following function:

<?php

function foo ()

{ return 5;}
?>

Operators in PHP.

What are Operators in PHP?

As in any programming language, PHP also has operators which are symbols (sometimes
keywords) that are predefined to perform certain commonly required operations on one or more
operands.

For example, using the expression "4 + 5" is equal to 9. Here "4" and "5" are called operands and
"+" is called an operator.

We have the following types of operators in PHP −

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. String Operators
6. Array Operators
7. Conditional (or Ternary Operators)

This chapter will provide an overview of how you can use these operators in PHP. In the
subsequent chapters, we will take a closer look at each of the operators and how they work.

Arithmetic Operators in PHP

We use Arithmetic operators to perform mathematical operations like addition, subtraction,


multiplication, division, etc. on the given operands. Arithmetic operators (excluding the
increment and decrement operators) always work on two operands, however the type of these
operands should be the same.

The following table highligts the arithmetic operators that are supported by PHP. Assume
variable "$a" holds 42 and variable "$b" holds 20 −

Operator Description Example

+ Adds two operands $a + $b = 62

- Subtracts second operand from the first $a - $b = 22

* Multiply both operands $a * $b = 840

/ Divide numerator by de-numerator $a / $b = 2.1


% Modulus Operator and remainder of after an integer division $a % $b = 2

++ Increment operator, increases integer value by one $a ++ = 43

-- Decrement operator, decreases integer value by one $a -- = 42

Comparison Operators in PHP

You would use Comparison operators to compare two operands and find the relationship between
them. They return a Boolean value (either true or false) based on the outcome of the comparison.

The following table highligts the comparison operators that are supported by PHP. Assume
variable $a holds 10 and variable $b holds 20, then −

Operat Description Example


or

== Checks if the value of two operands are equal or not, if yes then ($a == $b) is
condition becomes true. not true

!= Checks if the value of two operands are equal or not, if values are ($a != $b) is
not equal then condition becomes true. true

> Checks if the value of left operand is greater than the value of right ($a > $b) is
operand, if yes then condition becomes true. false

< Checks if the value of left operand is less than the value of right ($a < $b) is
operand, if yes then condition becomes true. true

>= Checks if the value of left operand is greater than or equal to the ($a >= $b) is
value of right operand, if yes then condition becomes true. false

<= Checks if the value of left operand is less than or equal to the value ($a <= $b) is
of right operand, if yes then condition becomes true. true

Logical Operators in PHP

You can use Logical operators in PHP to perform logical operations on multiple expressions
together. Logical operators always return Boolean values, either true or false.

Logical operators are commonly used with conditional statements and loops to return decisions
according to the Boolean conditions. You can also combine them to manipulate Boolean values
while dealing with complex expressions.
The following table high ligts the logical operators that are supported by PHP.

Assume variable $a holds 10 and variable $b holds 20, then −

Operator Description Example

and Called Logical AND operator. If both the operands are true (A and B) is true
then condition becomes true.

or Called Logical OR Operator. If any of the two operands are (A or B) is true


non zero then condition becomes true.

&& Called Logical AND operator. If both the operands are non (A && B) is true
zero then condition becomes true.

|| Called Logical OR Operator. If any of the two operands are (A || B) is true


non zero then condition becomes true.

! Called Logical NOT Operator. Use to reverses the logical !(A && B) is false
state of its operand. If a condition is true then Logical NOT
operator will make false.

Assignment Operators in PHP

You can use Assignment operators in PHP to assign or update the values of a given variable with
a new value. The right-hand side of the assignment operator holds the value and the left-hand
side of the assignment operator is the variable to which the value will be assigned.

The data type of both the sides should be the same, else you will get an error. The associativity of
assignment operators is from right to left. PHP supports two types of assignment operators −

​ Simple Assignment Operator − It is the most commonly used operator. It is used to assign
value to a variable or constant.
​ Compound Assignment Operators − A combination of the assignment operator (=) with
other operators like +, *, /, etc.

The following table highligts the assignment operators that are supported by PHP −

Operator Description Example

= Simple assignment operator, Assigns values from C = A + B will assign


right side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right C += A is equivalent to C


operand to the left operand and assign the result =C+A
to left operand
-= Subtract AND assignment operator, It subtracts C -= A is equivalent to C
right operand from the left operand and assign =C-A
the result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent to C


right operand with the left operand and assign the =C*A
result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent to C


operand with the right operand and assign the =C/A
result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent to C


modulus using two operands and assign the result =C%A
to left operand

String Operators in PHP

There are two operators in PHP for working with string data types −

​ The "." (dot) operator is PHP's concatenation operator. It joins two string operands
(characters of right hand string appended to left hand string) and returns a new string.
​ PHP also has the ".=" operator which can be termed as the concatenation assignment
operator. It updates the string on its left by appending the characters of right hand
operand.

$third=$first.$second;

$leftstring=$rightstring

Array Operators in PHP

PHP defines the following set of symbols to be used as operators on array data types −

Symbol Example Name Result

+ $a + $b Union Union of $a and $b.

== $a == $b Equality TRUE if $a and $b have the same key/value pairs.

=== $a === $b Identity TRUE if $a and $b have the same key/value pairs in the
same order and of the same types.

!= $a != $b Inequality TRUE if $a is not equal to $b.

<> $a <> $b Inequality TRUE if $a is not equal to $b.


!== $a !== $b Non TRUE if $a is not identical to $b.
identity

Conditional Operators in PHP

There is one more operator in PHP which is called conditional operator. It is also known as
ternary operator. It first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise value Y


Expression

Operator Categories in PHP

All the operators we have discussed above can be categorised into following categories −

​ Unary prefix operators, which precede a single operand.


​ Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
​ The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first expression.
​ Assignment operators, which assign a value to a variable.

Operator Precedence in PHP

Precedence of operators decides the order of execution of operators in an expression. For


example, in "2+6/3", division of 6/3 is done first and then the addition of "2+2" takes place
because the division operator "/" has higher precedence over the addition operator "+".

To force a certain operator to be called before other, parentheses should be used. In this example,
(2+6)/3 performs addition first, followed by division.

Some operators may have the same level of precedence. In that case, the order of associativity
(either left or right) decides the order of operations. Operators of same precedence level but are
non-associative cannot be used next to each other.

The following table lists the PHP operators in their decreasing order of precedence −

Operators Purpose

clone new clone and new


** exponentiation

++ -- increment/decrement

~(int) (float) (string) (array) (object) (bool) casting

instanceof types

! logical

*/ multiplication/division

% modulo

+-. arithmetic and string

<< >> bitwise shift

< <= > >= comparison

== != === !== <> <=> comparison

& bitwise and/references

^ bitwise XOR

| bitwise OR

&& logical and

|| logical or

?? null coalescing

?: ternary

= += -= *= **= /= .= %= &= |= ^= <<= >>= ??= assignment operators

yield from yield from

yield yield

print print

and logical

xor logical
or logical
Conditional statements:

The ability to implement conditional logic is the fundamental requirement of any programming
language (PHP included). PHP has three keywords (also called as language constructs) – if,
elseif and else – are used to take decision based on the different conditions.

The if keyword is the basic construct for the conditional execution of code fragments. More often
than not, the if keyword is used in conjunction with else keyword, although it is not always
mandatory.

If you want to execute some code if a condition is true and another code if the sme condition is
false, then use the "if....else" statement.

Syntax

The usage and syntax of the if statement in PHP is similar to that of the C language. Here is the
syntax of if statement in PHP −

if (expression)
code to be executed if expression is true;
else
code to be executed if expression is false;

The if statement is always followed by a Boolean expression.

​ PHP will execute the statement following the Boolean expression if it evaluates to true.
​ If the Boolean expression evaluates to false, the statement is ignored.
​ If the algorithm needs to execute another statement when the expression is false, it is
written after the else keyword.

<?php
$a=10;
$b=20;
if ($a > $b)
echo "a is bigger than b";
else
echo "a is not bigger than b";
?>

When the above code is run, it displays the following output −

a is not bigger than b

Using elseif in PHP

If you want to execute some code if one of the several conditions are true, then use the elseif
statement. The elseif language construct in PHP is a combination of if and else.

​ Similar to else, it specifies an alternative statement to be executed in case the original if


expression evaluates to false.
​ However, unlike else, it will execute that alternative expression only if the elseif
conditional expression evaluates to true.

if (expr1)
code to be executed if expr1 is true;
elseif (expr2)
code to be executed if expr2 is true;
else
code to be executed if expr2 is false;
EXAMPLE
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "<h3>Have a nice weekend!</h3>";

elseif ($d == "Sun")


echo "<h3>Have a nice Sunday!</h3>";

else
echo "<h3>Have a nice day!</h3>";
?>
</body>
</html>

On a Sunday, the browser shall display the following output −

Have a nice Sunday!


if, if-else,

Switch
The switch statement is followed by an expression, which is successively compared with value
in each case clause. If it is found that the expression matches with any of the cases, the
corresponding block of statements is executed.

​ The switch statement executes the statements inside the curly brackets line by line.
​ If and when a case statement is found whose expression evaluates to a value that matches
the value of the switch expression, PHP starts to execute the statements until the end of
the switch block, or the first time it encounters a break statement.
​ If you don't write a break statement at the end of a case's statement list, PHP will go on
executing the statements of the following case.

<?php
$x=0;
switch ($x) {
case 0:
echo "x equals 0 \n";
case 1:
echo "x equals 1 \n";
case 2:
echo "x equals 2 \n";
}
?>

It will produce the following output −

x equals 0
x equals 1
x equals 2

The ‘?’Operator,
One way of avoiding the verbosity of if and else statements is to use the more com‐ pact
ternary operator, ?, which is unusual in that it takes three operands rather than the typical two.
The ? operator is passed an expression that it must evaluate, along with two state‐ments to
execute: one for when the expression evaluates to TRUE, the other for when it is FALSE.

Looping statements: while Loop,

The easiest way to create a loop in a PHP script is with the while construct. The syntax of while
loop in PHP is similar to that in C language. The loop body block will be repeatedly executed as
long as the Boolean expression in the while statement is true.

The following flowchart helps in understanding how the while loop in PHP works −
The value of the expression is checked each time at the beginning of the loop. If the while
expression evaluates to false from the very beginning, the loop won't even be run once. Even if
the expression becomes false during the execution of the block, the execution will not stop until
the end of the iteration.

The syntax of while loop can be expressed as follows −

while (expr){
statements
}
EXAMPLE
<?php
$x = 1;
while ($x<=10) {
echo "Iteration No. $x \n";
$x++;
}
?>
It will produce the following output −

Iteration No. 1
Iteration No. 2
Iteration No. 3
Iteration No. 4
Iteration No. 5
Iteration No. 6
Iteration No. 7
Iteration No. 8
Iteration No. 9
Iteration No. 10

do-while Loop,

The "do…while" loop is another looping construct available in PHP. This type of loop is similar
to the while loop, except that the test condition is checked at the end of each iteration rather than
at the beginning of a new iteration.

The while loop verifies the truth condition before entering the loop, whereas in "do…while"
loop, the truth condition is verified before re entering the loop. As a result, the "do…while" loop
is guaranteed to have at least one iteration irrespective of the truth condition.

The following figure shows the difference in "while" loop and "do…while" loop by using a
comparative flowchart representation of the two.
The syntax for constituting a "do…while" loop is similar to its counterpart in C language.
do {
statements;
}
while (expression);
EXAMPLE
<?php
$i=1;
do{
echo "Iteration No: $i \n";
$i++;
}
while ($i<=5);
?>

It will produce the following output −

Iteration No: 1
Iteration No: 2
Iteration No: 3
Iteration No: 4
Iteration No: 5
for Loop.
The for statement is used when you know how many times you want to execute a statement or
a block of statements.

Syntax of "for" Loop

The syntax of for statement in PHP is similar to the for statement in C language.

for (expr1; expr2; expr3){


code to be executed;
}
EXAMPLE
<?php
for ($i=1; $i<=10; $i++){
echo "Iteration No: $i \n";
}
?>

Here is its output −

Iteration No: 1

Iteration No: 2

Iteration No: 3

Iteration No: 4

Iteration No: 5

Iteration No: 6

Iteration No: 7

Iteration No: 8

Iteration No: 9
Iteration No: 10

Foreach Loop

The foreach construct in PHP is specially meant for iterating over arrays. If you try to use it on a
variable with a different data type, PHP raises an error.

The foreach loop in PHP can be used with indexed array as well as associative array. There are
two types of usage syntaxes available −

foreach (array as $value) {

statements

The above method is useful when you want to iterate an indexed array. The syntax below is more
suitable for associative arrays.

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

statements

EXAMPLE

<?php

$arr = array(10, 20, 30, 40, 50);

foreach ($arr as $val) {

$index = array_search($val, $arr);

echo "Element at index $index is $val \n";

?>
It will produce the following output −

Element at index 0 is 10

Element at index 1 is 20

Element at index 2 is 30

Element at index 3 is 40

Element at index 4 is 50

You might also like