PHP Introduction2
PHP Introduction2
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.
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.
Let's see the example to store string, integer, and float values in PHP variables.
FILE: VARIABLE1.PHP
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
File: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:
In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.
File: variable3.php
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
Output:
My car is red
My house is
My boat is
File: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>
Output:
File: variableinvalid.php
<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)
echo "$4c <br/> $*d";
?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.
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."
Local variable
Global variable
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:
FILE: LOCAL_VARIABLE1.PHP
<?php
function local_var()
{
$num = 45;
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
echo $lang;
?>
Output:
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.
Example:
FILE: GLOBAL_VARIABLE1.PHP
<?php
$name = "Sanaya Sharma";
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside 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.
FILE: GLOBAL_VARIABLE2.PHP
<?php
$name = "Sanaya Sharma";
function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
Output:
Example:
File: global_variable3.php
<?php
$num1 = 5;
$num2 = 13;
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
Output:
Sum of global variables is: 18
If two variables, local and global, have the same name, then the local variable has higher priority than
the global variable inside the function.
Example:
FILE: GLOBAL_VARIABLE2.PHP
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Output:
Note: local variable has higher priority than the global variable.
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:
File: static_variable.php
<?php
function static_var()
{
static $num1 = 3;
$num2 = 6;
$num1++;
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
static_var();
static_var();
?>
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 $ AND $$ -
The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float,
etc.
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.
Example 1
<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>
Output:
In the above example, we have assigned a value to the variable x as abc. Value of reference variable $$x is
assigned as 200.
Example2
<?php
$x="U.P";
$$x="Lucknow";
echo $x. "<br>";
echo $$x. "<br>";
echo "Capital of $x is " . $$x;
?>
Output:
In the above example, we have assigned a value to the variable x as U.P. Value of reference variable $$x is
assigned as Lucknow.
Example3
<?php
$name="Cat";
${$name}="Dog";
${${$name}}="Monkey";
echo $name. "<br>";
echo ${$name}. "<br>";
echo $Cat. "<br>";
echo ${${$name}}. "<br>";
echo $Dog. "<br>";
?>
Output:
In the above example, we have assigned a value to the variable name Cat. Value of reference variable $
{$name} is assigned as Dog and ${${$name}} as Monkey.
PHP CONSTANTS -
PHP constants are name or identifier that can't be changed during the execution of the script except for magic
constants, which are not really constants. PHP constants can be defined by 2 ways:
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.
Note: Unlike variables, constants are automatically global throughout the script.
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)
case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case
sensitive by default.
FILE: CONSTANT1.PHP
<?php
define("MESSAGE","Hello PHP");
echo MESSAGE;
?>
Output:
Hello PHP
FILE: CONSTANT2.PHP
<?php
define("MESSAGE","Hello PHP",true);//not case sensitive
echo MESSAGE, "</br>";
echo message;
?>
Output:
Hello PHP
Hello PHP
FILE: CONSTANT3.PHP
<?php
define("MESSAGE","Hello PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
Hello PHP
in C:\wamp\www\vconstant3.php on line 4
message
PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It
is a language construct, not a function. The constant defined using const keyword are case-sensitive.
FILE: CONSTANT4.PHP
<?php
const MESSAGE="Hello const by PHP";
echo MESSAGE;
?>
Output:
CONSTANT() FUNCTION
There is another way to print the value of constants using constant() function instead of using the echo
statement.
Syntax
constant (name)
FILE: CONSTANT5.PHP
<?php
define("MSG", "");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Output:
CONSTANT VS VARIABLES
Constant Variables
Once the constant is defined, it can never be redefined. A variable can be undefined as well as redefined
easily.
A constant can only be defined using define() function. A variable can be defined by simple assignment
It cannot be defined by any simple assignment. (=) operator.
There is no need to use the dollar ($) sign before To declare a variable, always use the dollar ($)
constant during the assignment. sign before the variable.
Constants do not follow any variable scoping rules, and Variables can be declared anywhere in the
they can be defined and accessed anywhere. program, but they 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.
It holds only single value. There are 4 scalar data types in PHP.
boolean
integer
float
string
It can hold multiple values. There are 2 compound data types in PHP.
array
object
resource
NULL
PHP BOOLEAN
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often
used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
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.
EXAMPLE:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
HexaDecimal number: 69
PHP FLOAT
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional
or decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
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:
<?php
$company = "";
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello
Hello $company
PHP ARRAY
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes);
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
You will learn more about array in later chapters of this tutorial.
PHP OBJECT
Objects are the instances of user-defined classes that can store both values and functions. They must be
explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
PHP RESOURCE
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or
references to external PHP resources. For example - a database call. It is an external resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP NULL
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as
it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl;
?>
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:
$num=10+20;
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
Arithmetic Operators
Assignment Operators
Bitwise Operators
Comparison Operators
Incrementing/Decrementing Operators
Logical Operators
String Operators
Array Operators
Type Operators
Execution Operators
Error Control Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
ARITHMETIC OPERATORS
The PHP arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, etc. with numeric values.
ASSIGNMENT OPERATORS
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".
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.
COMPARISON OPERATORS
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
INCREMENTING/DECREMENTING OPERATORS
The increment and decrement operators are used to increase and decrease the value of a variable.
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.
STRING OPERATORS
The string operators are used to perform the operation on strings. There are two string operators in PHP,
which are given below:
ARRAY OPERATORS
The array operators are used in case of array. Basically, these operators are used to compare the values of
arrays.
TYPE OPERATORS
The type operator instanceof is used to determine whether an object, its parent and its derived class are the
same type or not. Basically, this operator determines which certain class the object belongs to. It is used in
object-oriented programming.
<?php
//class declaration
class Developer
{}
class Programmer
{}
//creating an object of type Developer
$charu = new Developer();
//testing the type of object
if( $charu instanceof Developer)
{
echo "Charu is a developer.";
}
else
{
echo "Charu is a programmer.";
}
echo "</br>";
var_dump($charu instanceof Developer); //It will return true.
var_dump($charu instanceof Programmer); //It will return false.
?>
Output:
Charu is a developer.
bool(true) bool(false)
EXECUTION OPERATORS
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command.
Execution operator and shell_exec() give the same result.
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression, any error
message will be ignored that might be generated by that expression.
PHP COMMENTS -
PHP comments can be used to describe any line of code so that other developer can understand the
code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style
(Unix shell style) comments.
<?php
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>
Output:
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let's see a
simple example of PHP multiple line comment.
<?php
echo "Welcome to PHP multi line comment";
?>
Output:
PHP IF ELSE -
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
if
if-else
if-else-if
nested if
PHP IF STATEMENT
If statement is used to executes the block of code exist inside the if statement only if the specified condition is
true.
Syntax
Flowchart
EXAMPLE
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
If-else statement is slightly different from if statement. It executes one block of code if the specified condition
is true and another block of code if the condition is false.
Syntax
Flowchart
EXAMPLE
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check
multiple conditions using this statement.
Syntax
if (condition1){
} elseif (condition2){
} elseif (condition3){
....
} else{
}
Flowchart
EXAMPLE
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
The nested if statement contains the if block inside another if block. The inner if statement executes only when
specified condition in outer if statement is true.
Syntax
if (condition) {
if (condition) {
}
}
Flowchart
EXAMPLE
<?php
$age = 23;
$nationality = "Indian";
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
Output:
$a = 34; $b = 56; $c = 45;
if ($a < $b) {
if ($a < $c) {
echo "$a is smaller than $b and $c";
}
}
?>
Output:
PHP SWITCH -
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if
statement.
Syntax
switch(expression){
case value1:
break;
case value2:
break;
......
default:
code to be executed if all cases are not matched;
}
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
<?php
$ch = 'U';
switch ($ch)
{
case 'a':
echo "Given character is vowel";
break;
case 'e':
echo "Given character is vowel";
break;
case 'i':
echo "Given character is vowel";
break;
case 'o':
echo "Given character is vowel";
break;
case 'u':
echo "Given character is vowel";
break;
case 'A':
echo "Given character is vowel";
break;
case 'E':
echo "Given character is vowel";
break;
case 'I':
echo "Given character is vowel";
break;
case 'O':
echo "Given character is vowel";
break;
case 'U':
echo "Given character is vowel";
break;
default:
echo "Given character is consonant";
break;
}
?>
<?php
$ch = "B.Tech";
switch ($ch)
{
case "BCA":
echo "BCA is 3 years course";
break;
case "Bsc":
echo "Bsc is 3 years course";
break;
case "B.Tech":
echo "B.Tech is 4 years course";
break;
case "B.Arch":
echo "B.Arch is 5 years course";
break;
default:
echo "Wrong Choice";
break;
}
?>
Output:
<?php
$ch = 'c';
switch ($ch)
{
case 'a':
echo "Choice a";
break;
case 'b':
echo "Choice b";
break;
case 'c':
echo "Choice c";
echo "</br>";
case 'd':
echo "Choice d";
echo "</br>";
default:
echo "case a, b, c, and d is not found";
}
?>
Output:
Choice c
Choice d
<?php
$car = "Hyundai";
$model = "Tucson";
switch( $car )
{
case "Honda":
switch( $model )
{
case "Amaze":
echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
break;
case "City":
echo "Honda City price is 9.91 - 14.31 Lakh.";
break;
}
break;
case "Renault":
switch( $model )
{
case "Duster":
echo "Renault Duster price is 9.15 - 14.83 L.";
break;
case "Kwid":
echo "Renault Kwid price is 3.15 - 5.44 L.";
break;
}
break;
case "Hyundai":
switch( $model )
{
case "Creta":
echo "Hyundai Creta price is 11.42 - 18.73 L.";
break;
case "Tucson":
echo "Hyundai Tucson price is 22.39 - 32.07 L.";
break;
case "Xcent":
echo "Hyundai Xcent price is 6.5 - 10.05 L.";
break;
}
break;
}
?>
Output:
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is
used when you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
for(initialization; condition; increment/decrement){
}
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
EXAMPLE
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it
will execute infinite.
<?php
$i = 1;
for (;;) {
echo $i++;
echo "</br>";
}
?>
Output:
EXAMPLE
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
<?php
for ($i = 1; $i <= 9; $i++) {
echo $i;
}
echo "</br>";
for ($i = 1; ; $i++) {
if ($i > 9) {
break;
}
echo $i;
}
echo "</br>";
$i = 1;
for (; ; ) {
if ($i > 9) {
break;
}
echo $i;
$i++;
}
echo "</br>";
for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
?>
Output:
123456789
123456789
123456789
123456789
We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only
when the outer for loop condition is found true.
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is
to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for
1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
EXAMPLE
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>
Output:
11
12
13
21
22
23
31
32
33
Syntax
foreach( $array as $var ){
}
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
Output:
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
foreach ($array as $value) {
}
Syntax
foreach ($array as $key => $element) {
}
Flowchart
EXAMPLE 1:
PHP program to print array elements using foreach loop.
<?php
$season = array ("Summer", "Winter", "Autumn", "Rainy");
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
Output:
Summer
Winter
Autumn
Rainy
EXAMPLE 2:
PHP program to print associative array elements using foreach loop.
<?php
$employee = array (
"Name" => "Alex",
"Email" => "[email protected]",
"Age" => 21,
"Gender" => "Male"
);
foreach ($employee as $key => $element) {
echo $key . " : " . $element;
echo "</br>";
}
?>
Output:
Name : Alex
Email : [email protected]
Age : 21
Gender : Male
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>
Output:
Example 4:
Dynamic array
<?php
foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
echo "$elements\n";
}
?>
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
Alternative Syntax
while(condition):
endwhile;
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
Alternative Example
<?php
$n=1;
while($n<=10):
echo "$n<br/>";
$n++;
endwhile;
?>
Output:
Example
$i = 'A';
while ($i < 'H') {
echo $i;
$i++;
echo "</br>";
}
?>
Output:
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer
while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9
times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
EXAMPLE
<?php
$i=1;
while($i<=3){
$j=1;
while($j<=3){
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>
Output:
11
12
13
21
22
23
31
32
33
Syntax
Example
<?php
while (true) {
echo "Hello !";
echo "</br>";
}
?>
Output:
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is
guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have to
execute the loop at least once and the number of iterations is not even fixed, it is recommended to
use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas do-
while loop checks the condition at the end of the loop.
Syntax
do{
}while(condition);
Flowchart
EXAMPLE
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
6
7
10
EXAMPLE
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is
must that the program should not contain any other statements after the do-while loop. In this case, it will not
generate any error.
<?php
$x = 5;
do {
echo "Welcome to ! </br>";
$x++;
} while ($x < 10);
?>
Output:
Welcome to !
Welcome to !
Welcome to !
Welcome to !
Welcome to !
EXAMPLE
The following example will increment the value of $x at least once. Because the given condition is false.
<?php
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x;
?>
Output:
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
Flowchart
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
if($i==2 && $j==2){
break;
}
}
}
?>
Output:
11
12
13
21
22
31
32
33
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
Output:
$number = array ("One", "Two", "Three", "Stop", "Four");
foreach ($number as $element) {
if ($element == "Stop") {
break;
}
echo "$element </br>";
}
?>
Output:
You can see in the above output, after getting the specified condition true, break statement immediately ends
the loop and control is came out from the loop.
<?php
$car = 'Mercedes Benz';
switch ($car) {
default:
echo '$car is not Mercedes Benz<br>';
case 'Orange':
echo '$car is Mercedes Benz';
}
?>
Output:
<?php
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At matched condition i = 5<br />\n";
break 1;
case 10:
echo "At matched condition i = 10; quitting<br />\n";
break 2;
default:
break;
}
}?>
Output:
At matched condition i = 5
Note: The break keyword immediately ends the execution of the current structure.
PHP CONTINUE -
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
jump-statement;
continue;
Flowchart:
Example
In the following example, we will print only those values of i and j that are same and skip others.
<?php
for ($i =1; $i<=3; $i++) {
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue;
}
echo $i.$j;
echo "</br>";
}
}
?>
Output:
EXAMPLE
In the following example, we will print the even numbers between 1 to 20.
<?php
echo "Even numbers between 1 to 20: </br>";
$i = 1;
while ($i<=20) {
if ($i %2 == 1) {
$i++;
continue;
}
echo $i;
echo "</br>";
$i++;
}
?>
Output:
10
12
14
16
18
20
The following example prints the value of array elements except those for which the specified condition is true
and continue statement is used.
<?php
$number = array ("One", "Two", "Three", "Stop", "Four");
foreach ($number as $element) {
if ($element == "Stop") {
continue;
}
echo "$element </br>";
}
?>
Output:
Example
<?php
for ($i =1; $i<=3; $i++) {
for ($j=1; $j<=3; $j++) {
if (($i == $j) ) {
continue 1;
}
echo $i.$j;
echo "</br>";
}
}
?>