0% found this document useful (0 votes)
28 views60 pages

Php1 and 2unit Notes

Uploaded by

Chandana Gouda
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)
28 views60 pages

Php1 and 2unit Notes

Uploaded by

Chandana Gouda
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/ 60

Chapter 1

PHP
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source
general-purpose scripting language that is especially suited for web development and can be
embedded into HTML. It allows web developers to create dynamic content that interacts with
databases. PHP is basically used for developing web based software applications.
PHP is mainly focused on server-side scripting, so you can do anything any other CGI
program can do, such as collect form data, generate dynamic page content, or send and
receive cookies. Code is executed in servers, that is why you’ll have to install a sever-like
environment enabled by programs like XAMPP which is an Apache distribution.

1.1 Introduction

Back in 1994, Rasmus Lerdorf unleashed the very first version of PHP. However, now the
reference implementation is now produced by The PHP Group. The term PHP originally
stood for Personal Home Page but now it stands for the recursive acronym: Hypertext
Preprocessor. PHP 4 and PHP 5 are distributed under the PHP Licence v3.01, which is an
Open Source licence certified by the Open Source Initiative.

pg. 1
[Document title]

Why PHP?

There stand convincing arguments for all those who wonder why PHP is so popular today:

• Compatible with almost all servers used nowadays

A web server is an information technology that processes requests via HTTP, the basic
network protocol used to distribute information on the World Wide Web. There exist many
types of web servers that servers use. Some of the most important and well-known are:
Apache HTTP Server, IIS (Internet Information Services), lighttpd, Sun Java System Web
Server etc. As a matter of fact, PHP is compatible with all these web servers and many more.

• PHP will run on most platforms

Unlike some technologies that require a specific operating system or are built specifically
for that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux,
Unix etc)

• PHP supports such a wide range of databases

An important reason why PHP is so used today is also related to the various databases it
supports (is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo,
MaxDB, MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so
on.

• PHP is free to download and open source

Anyone can start using PHP right now by downloading it from php.net. Millions of people
are using PHP to create dynamic content and database-related applications that make for
outstanding web systems. PHP is also open source, which means the original source code is
made freely available and may be redistributed and modified.

• Easy to learn & large community

PHP is a simple language to learn step by step. This makes it easier for people to get engaged
in exploring it. It also has such a huge community online that is constantly willing to help
you whenever you’re stuck (which actually happens quite a lot).
The graphic below shows a basic workflow of dynamic content being passed to and from the
client using PHP:
Figure 1.1: PHP Dynamic Content Interaction

XAMPP Setup

XAMPP is a free and open source cross-platform web server solution developed by Apache Friends, consisting mainly of the
Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages. In
order to make your PHP code execute locally, first install XAMPP.

• Download XAMPP
• Install the program (check the technologies you want during installation)

• Open XAMPP and click on "Start" on Apache and MySQL (when working with databases)
Figure 1.2: XAMPP window after a successful installation with Apache and MySQL enabled

• Place your web project inside the htdocsdirectory. In the common case, if you installed XAMPP directly inside the C: driveof
your PC, the path to this folder would be: C:xampphtdocs

Figure 1.3: XAMPP Directory for Web Projects

To test the services are up and running you can just enter localhost in your address bar and
expect the welcoming page.
PHP Language Basics

The aim of this section is to introduce the general syntax you should expect in PHP.

Escaping to PHP

There are four ways the PHP parser engine can differentiate PHP code in a webpage:
• Canonical PHP Tags
This is the most popular and effective PHP tag style and looks like this:
<?php...?>

• Short-open Tags

These are the shortest option, but they might need a bit of configuration, and you might
either choose the --enable-short-tags configuration option when building PHP, or set the
short_open_tag setting in your php.ini file.
<?...?>

• ASP-like Tags

In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%...%>

• HTML script Tags

You can define a new script with an attribute language like so:
<script language="PHP">...</script>

1.1.1 Commenting PHP

Just like other languages, there are several ways to comment PHP code. Let’s
have a look at the most useful ones: Use #to write single-line comments
<?
# this is a comment in PHP, a single line comment
?>
<?
// this is also a comment in PHP, a single line comment
?>

Use // to also write single-line comments


Use /* ...*/ to write multi-line comments
<?
/* this is a multi line comment
Name: Web Code Geeks
Type: Website
Purpose: Web Development
*/
?>
Hello World

The very basic example of outputting a text in PHP would be:


<?
print("Hello World");
echo "Hello World";
printf("Hello World");
?>

The result of the above statements would be the same: "Hello World". But why are there three different ways to output?

• print returns a value. It always returns 1.


• echo can take a comma delimited list of arguments to output.

• printf is a direct analog of C’s printf().

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

o An integer can be either positive or negative.


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

Example:

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. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>

Output:

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

Example:

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

Keywords in Php:

What are PHP Keywords?


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.

List of PHP Keywords


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 , enddeclare ,endfor , endforeach ,endif
endswitch ,endwhile , extends, final , finally , for,
foreach , function , global , goto , if , implements
include , include_once , instanceof, insteadof, interface,
isset , 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
Copy.
Usage of PHP Keywords
Keywords are used in PHP to define certain statements, constructs, and functions. For example,
the if keyword is used to define a conditional statement, the while keyword is used to define a
loop, and the function keyword is used to define a function.
Here is an example of using some of the PHP keywords:
<?php

$x = 7;
// Define a conditional statement
if ($x == 5) {
echo "x is equal to 5.";
}

// Define a loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}

// Define a function
function add($a, $b)
{
return $a + $b;
}
?>
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script . 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.

PHP Constant: define()

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

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.

Ex:

<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>

Output:

Hello JavaTpoint 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.

<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>

Output:

Hello const by JavaTpoint PHP

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

Syntax :The syntax for the following constant function:


constant (name)

Example:

<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>

Variables in PHP
Any type of variable in PHP starts with a leading dollar sign ($) and is assigned a variable
type using the = (equals) sign. The value of a variable is the value of its most recent
assignment.

Creating (Declaring) PHP Variables


In PHP, a variable starts with the $ sign, followed by the name of the variable:

Syntax :

$variablename=value;

Example
$x = 5;

$y = "John"

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

Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Rules for PHP variables:

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

Example:

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

Constant vs Variables

Constant Variables

Once the constant is defined, it can never be A variable can be undefined as well as redefined easily.
redefined.

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

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

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

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

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


PHP Programming Cookbook 15 / 63

PHP Variable Scope


The scope of a variable is defined as its range in the program under which it can be accessed. In other words,
"The scope of a variable is the portion of the program within which it is defined and can be accessed."

PHP has three types of variable scopes:

1. Local variable
2. Global variable
3. Static variable

Local variable
The variables that are declared within a function are called local variables for that function. These local variables
have their scope only in that particular function in which they are declared. This means that these variables
cannot be accessed outside the function, as they have local scope.

A variable declaration outside the function with the same name is completely different from the variable declared
inside the function. Let's understand the local variables with the help of an example:

1. <?php
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>

Output:

Local variable declared inside the function is: 45

Ex:
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
//using $lang (local variable) outside the function will generate an error
PHP Programming Cookbook 16 / 63

echo $lang;
?>

Output:

Web development language: PHP

Global variable
The global variables are the variables that are declared outside the function. These variables can be accessed
anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the
variable. However, these variables can be directly accessed or used outside the function without any keyword.
Therefore there is no need to use any keyword to access a global variable outside the function.

Let's understand the global variables with the help of an ex:

Example:

1. <?php
2. $name = "Sanaya Sharma"; //Global Variable
3. function global_var()
4. {
5. global $name;
6. echo "Variable inside the function: ". $name;
7. echo "</br>";
8. }
9. global_var();
10. echo "Variable outside the function: ". $name;
11. ?>

Output:

Variable inside the function: Sanaya Sharma


Variable outside the function: Sanaya Sharma
Note: Without using the global keyword, if you try to access a global variable inside the function, it will generate an
error that the variable is undefined.
PHP Programming Cookbook 17 / 63

Static variable

It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we
need to store a variable even after completion of function execution. Therefore, another important feature of
variable scoping is static variable. We use the static keyword before the variable to define a variable, and this
variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program execution leaves
the scope. Understand it with the help of an example:

Example:

1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6. //increment in non-static variable
7. $num1++;
8. //increment in static variable
9. $num2++;
10. echo "Static: " .$num1 ."</br>";
11. echo "Non-static: " .$num2 ."</br>";
12. }
13.
14. //first function call
15. static_var();

16. //second function call


17. static_var();
18. ?>

Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is
why because $num1 is not a static variable, so it freed its memory after the execution of each function call.
PHP Programming Cookbook 18 / 63

PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:

1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:

o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc.
with numeric values.
PHP Programming Cookbook 19 / 63

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b

*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b

/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b


(quotient)

%= Divide then Assign $a %= $b Find remainder same as $a = $a % $b


(remainder)
PHP Programming Cookbook 20 / 63

Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.

| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places

Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:

Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b

=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type

!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b


PHP Programming Cookbook 21 / 63

<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b

>= Greater than or equal $a >= $b Return TRUE if $a is greater than or equal $b
to

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- decrement --$a Decrement the value of $a by one, then return $a

$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.

Operator Name Example Explanation

and And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true


PHP Programming Cookbook 22 / 63

String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which are
given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the concatenated
Assignment string to $a, e.g. $a = $a . $b

Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.

Operator Name Example Explanation

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

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

=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same type in
same order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity

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

Control statements in php:

For controlling the flow of the program, the control statements are beneficial
for the flow of execution of statements.
The Control Statements in PHP are divided into three types which
are Conditional/Selection statements, Iteration/Loop statements, and Jump statements.
PHP Programming Cookbook 23 / 63

CONDITIONAL STATEMENTS IN PHP

Conditional statements are used to execute different code based on different


conditions. PHP | Decision Making

••
PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would be
performed as asked by the user. It’s just like a two- way path. If you want something then go this
way or else turn that way. To use this feature, PHP provides us with four conditional statements:
• if statement
• if…else statement
• if…elseif…else statement
• switch statement
Let us now look at each one of these in details:
1. if Statement: This statement allows us to set a condition. On being TRUE, the following
block of code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
Example:

<?php
$x = 12;

if ($x > 0) {
echo "The number is positive";
}
?>

Output:
The number is positive

Flowchart:
PHP Programming Cookbook 24 / 63

2. if…else Statement: We understood that if a condition will hold i.e., TRUE, then the block
of code within if will be executed. But what if the condition is not TRUE and we want to
perform an action? This is where else comes into play. If a condition is TRUE then if block
gets executed, otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:

<?php
$x = -12;

if ($x > 0) {
echo "The number is positive";
}

else{
echo "The number is negative";
}
PHP Programming Cookbook 25 / 63

?>

Output:
The number is negative
Flowchart:

3. if…elseif…else Statement: This allows us to use multiple if…else statements. We use this
when there are multiple conditions of TRUE cases.
Syntax:
4. if (condition) {
5. // if TRUE then execute this code
6. }
7. elseif {
8. // if TRUE then execute this code
9. }
10. elseif {
11. // if TRUE then execute this code
12. }
13. else {
PHP Programming Cookbook 26 / 63

14. // if FALSE then execute this code


15. }
Example:

<?php
$x = "August";

if ($x == "January") {
echo "Happy Republic Day";
}

elseif ($x == "August") {


echo "Happy Independence Day!!!";
}

else{
echo "Nothing to show";
}
?>

Output:
Happy Independence Day!!!
Flowchart:
PHP Programming Cookbook 27 / 63

switch Statement: The “switch” performs in various cases i.e., it has various cases to which it
matches the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same case
is executed. To use switch, we need to get familiar with two different keywords
namely, break and default.
1. The break statement is used to stop the automatic control flow into the next
cases and exit from the switch case.
2. The default statement contains the code that would execute if none of the cases
match.
PHP Programming Cookbook 28 / 63

Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;

Example:

<?php
$n = "February";

switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
PHP Programming Cookbook 29 / 63

echo "Its June";


break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>

Output:
Its February
Flowchart:
PHP Programming Cookbook 30 / 63
PHP Programming Cookbook 31 / 63

Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of writing if…else,
called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three
operands: a condition to check, a result for TRUE and a result for FALSE.
Syntax:

(condition) ? if TRUE execute this : otherwise execute this;


Example:

<?php
$x = -12;

if ($x > 0) {
echo "The number is positive \n";
}
else {
echo "The number is negative \n";
}

// This whole lot can be written in a


// single line using ternary operator
echo ($x > 0) ? 'The number is positive' :
'The number is negative';
?>

Output:
The number is negative
The number is negative

Loops in PHP

In PHP, just like any other programming language, loops are used to execute the same code block
for a specified number of times. Except for the common loop types (for, while, do. . . while),
PHP also support foreach loops, which is not only specific to PHP. Languages like Javascript
and C# already use foreach loops. Let’s have a closer look at how each of the loop types
works.

PHP For Loop


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

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

It allows users to put all the loop related statements in one place. See in the syntax given below:
PHP Programming Cookbook 32 / 63

Syntax

1. for(initialization; condition; increment/decrement){


2. //code to be executed
3. }

Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:

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

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

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

Flowchart
PHP Programming Cookbook 33 / 63

Example

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

Output:

1
2
3
4
5
6
7
8
9
10

PHP While Loop


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

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

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

Syntax

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

Alternative Syntax

1. while(condition):
2. //code to be executed
3.
4. endwhile;

PHP While Loop Flowchart


PHP Programming Cookbook 34 / 63

PHP While Loop Example

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

Output:

1
2
3
4
5
6
7
8
9
10

PHP do-while loop


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

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

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

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

Syntax

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

Flowchart

Example

1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
PHP Programming Cookbook 36 / 63

Output:

1
2
3
4
5
6
7
8
9
PHP foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if
you try to use it with the variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an
array.

In foreach loop, we don't need to increment the value.

Syntax

1. foreach ($array as $value) {


2. //code to be executed
3. }

There is one more syntax of foreach loop.

Syntax

1. foreach ($array as $key => $element) {


2. //code to be executed
3. }

Flowchart
Example 1:
PHP program to print array elements using foreach loop.

1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>

Output:

Summer
Winter
Autumn
Rainy

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

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

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

Syntax

jump statement;
break;

Flowchart
PHP Break: inside loop
Let's see a simple example to break the execution of for loop if value of i is equal to 5.

ADVERTISEMENT

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

Output:

1
2
3
4

PHP continue statement


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

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

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

jump-statement;
continue;

Flowchart:

PHP Continue Example with for loop


Example

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

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

Output:

11
22
33

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

Advantage of PHP Array


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

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

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

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

PHP Indexed Array


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

1st way:

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

2nd way:

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

Output:Season are: summer, winter, spring and autumn

Example:

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

Output:

Season are: summer, winter, spring and autumn

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>

Output:
3

Traversing PHP Indexed Array


We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all the elements of
PHP array.

File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

Output:

Size is: Big


Size is: Medium
Size is: Short

PHP Associative Array


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

There are two ways to define associative array:

1st way:

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

2nd way:

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

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

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

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 20000

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>

Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000

PHP Access Arrays


access Array Item
To access an array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.

Ex:
Access an item by referring to its index number:
$cars = array("Volvo", "BMW", "Toyota");

echo $cars[2];

To access items from an associative array, use the key name:

Example
Access an item by referring to its key name:

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);

echo $cars["year"];

Example
Display all array items, keys and values:by using foeeach loop

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

foreach ($car as $x => $y) {

echo "$x: $y <br>";

PHP Multidimensional Array


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

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

Array function in PHP:


1.PHP array() Function
Definition and Usage
The array() function is used to create an array.

Syntax
Syntax for indexed arrays:

array(value1, value2, value3, etc.)

Syntax for associative arrays:

array(key=>value,key=>value,key=>value,etc.)

Parameter Values

Parameter Description

key Specifies the key (numeric or string)

value Specifies the value

Example:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Output:

Peter is 35 years old.

2. PHP array_key_exists() Function


Definition and Usage
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the
key does not exist.
Tip: Remember that if you skip the key when you specify an array, an integer key is generated, starting at 0 and
increases by 1 for each value.

Syntax
array_key_exists(key, array)

Parameter Values

Parameter Description

key Required. Specifies the key

array Required. Specifies an array

ExampleGet your own PHP Server


Check if the key "Volvo" exists in an array:

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>

3.PHP array_keys() Function

Definition and Usage


The array_keys() function returns an array containing the keys.

Syntax
array_keys(array, value, strict)
Parameter Values

Parameter Description

array Required. Specifies an array

value Optional. You can specify a value, then only the keys with this value are returned

strict Optional. Used with the value parameter. Possible values:

• true - Returns the keys with the specified value, depending on type: the number 5
• false - Default value. Not depending on type, the number 5 is the same as the str

Example
Return an array containing the keys:

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>

Output:Array ( [0] => Volvo [1] => BMW [2] => Toyota )

4.PHP array_merge()
Definition and Usage
The array_merge() function merges one or more arrays into one array.

Tip: You can assign one array to the function, or as many as you like.

Note: If two or more array elements have the same key, the last one overrides the others.

Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new
array with integer keys starting at 0 and increases by 1 for each value (See example below).

Tip: The difference between this function and the array_merge_recursive() function is when two or more array
elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an
array.
Syntax
array_merge(array1, array2, array3, ...)

Parameter Values

Parameter Description

array1 Required. Specifies an array

array2 Optional. Specifies an array

array3,... Optional. Specifies an array

Example
Merge two arrays into one array:

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )
5.PHP array_pop() Function

Definition and Usage


The array_pop() function deletes the last element of an array.

Syntax
array_pop(array)
Parameter Values

Parameter Description

array Required. Specifies an array

Example
Delete the last element of an array:

<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output:
Array ( [0] => red [1] => green )

6.PHP array_push() Function

Definition and Usage


The array_push() function inserts one or more elements to the end of an array.

Tip: You can add one value, or as many as you like.

Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

Syntax
array_push(array, value1, value2, ...)

Parameter Values

Parameter Description

array Required. Specifies an array


value1 Optional. Specifies the value to add (Required in PHP versions before 7.3)

value2 Optional. Specifies the value to add

Example
Insert "blue" and "yellow" to the end of an array:

<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>

Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )

7.PHP array_search() Function

Definition and Usage


The array_search() function search an array for a value and returns the key.

Syntax
array_search(value, array, strict)

Parameter Values

Parameter Description
value Required. Specifies the value to search for

array Required. Specifies the array to search in

strict Optional. If this parameter is set to TRUE, then this function will search for identical
elements in the array. Possible values:

• true
• false - Default

ADVERTISEMENT

Example
Search an array for the value "red" and return its key:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>

8.PHP array_shift() Function

Definition and Usage


The array_shift() function removes the first element from an array, and returns the value of the removed element.

Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

Syntax
array_shift(array)
Parameter Values
Parameter Description

array Required. Specifies an array

Example
Remove the first element (red) from an array, and return the value of the removed element:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
?>

9.PHP array_slice() Function


Definition and Usage
The array_slice() function returns selected parts of an array.

Note: If the array have string keys, the returned array will always preserve the keys (See example 4).

Syntax
array_slice(array, start, length, preserve)

Parameter Values

Parameter Description

array Required. Specifies an array


start Required. Numeric value. Specifies where the function will start the slice. 0 = the first
element. If this value is set to a negative number, the function will start slicing that far
from the last element. -2 means start at the second last element of the array.

length Optional. Numeric value. Specifies the length of the returned array. If this value is set to
a negative number, the function will stop slicing that far from the last element. If this
value is not set, the function will return all elements, starting from the position set by the
start-parameter.

preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:

• true - Preserve keys


• false - Default. Reset keys

Example
Start the slice from the third array element, and return the rest of the elements in the array:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

10.PHP array_slice() Function

Definition and Usage


The array_slice() function returns selected parts of an array.

Note: If the array have string keys, the returned array will always preserve the keys (See example 4).

Syntax
array_slice(array, start, length, preserve)
Parameter Values

Parameter Description

array Required. Specifies an array

start Required. Numeric value. Specifies where the function will start the slice. 0 = the first
element. If this value is set to a negative number, the function will start slicing that far from
the last element. -2 means start at the second last element of the array.

length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a
negative number, the function will stop slicing that far from the last element. If this value is
not set, the function will return all elements, starting from the position set by the start-
parameter.

preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:

• true - Preserve keys


• false - Default. Reset keys

Example
Start the slice from the third array element, and return the rest of the elements in the array:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

11.PHP array_splice() Function


Definition and Usage
The array_splice() function removes selected elements from an array and replaces it with new elements. The function
also returns an array with the removed elements.

Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of
the start parameter (See Example 2).
Note: The keys in the replaced array are not preserved.

Parameter Description

array Required. Specifies an array

start Required. Numeric value.

length Optional. Numeric value. Specifies how many elements will be removed.

array Optional. Specifies an array with the elements that will be inserted to the original array.

Syntax
array_splice(array, start, length, array)

Parameter Values

Example
Remove elements from an array and replace it with new elements:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
12.PHP count() Function
Definition and Usage
The count() function returns the number of elements in an array.

Syntax
count(array, mode)

Parameter Values

Parameter Description

array Required. Specifies the array

mode Optional. Specifies the mode. Possible values:

• 0 - Default. Does not count all elements of multidimensional arrays


• 1 - Counts the array recursively (counts all the elements of multidimensional
arrays)

Example
Return the number of elements in an array:

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Difference between Indexed array and associative array:

Indexed Array Associative Array

The keys of an indexed array are integers which start at 0. Keys may be strings in the case of an associative array.

They are like single-column tables. They are like two-column tables.

They are not maps. They are known as maps.

PHP include and require Statements


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

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

• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue

Syntax
include 'filename';

or

require 'filename';

example:

<html>
<body>

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


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

</body>
</html>
Difference between require() and include() Functions:
include() require()

The include() function does not stop the


The require() function will stop the execution of the
execution of the script even if any error
script when an error occurs.
occurs.

The include() function does not give a fatal


The require() function gives a fatal error
error.

The include() function is mostly used when


the file is not required and the application The require() function is mostly used when the file is
should continue to execute its process when mandatory for the application.
the file is not found.

The include() function will only produce a The require() will produce a fatal error
warning (E_WARNING) and the script will (E_COMPILE_ERROR) along with the warning and
continue to execute. the script will stop its execution.

The include() function generate various The require() function is more in recommendation and
functions and elements that are reused considered better whenever we need to stop the
across many pages taking a longer time for execution incase of availability of file, it also saves
the process completion. time avoiding unnecessary inclusions and generations.

You might also like