PHP Expressions & Control Statements
PHP Expressions & Control Statements
• PHP is implemented in C and C++.Initially Ramsus Lerdorf wrote PHP to maintain his personal
home page later extended it to communicate with data bases, file systems and work with web
forms and called this implementation as PHP/FI (Personal Home Page/ Forms Interpreter).
• PHP 3 (1998): The first version considered suitable for widespread use.
• PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
• PHP 5 (2004): Added object-oriented programming features.
• PHP 7 (2015): Significant performance improvements and reduced memory usage.
• PHP 8 (2020): Introduction of Just-In-Time (JIT) compilation, further enhancing performance.
Advantages of PHP
<?php
// PHP code goes here
?>
PHP Example
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!”;
?>
</body>
</html>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
• PHP statements end with a semicolon (;)
Comments in PHP
• A comment in PHP code is a line that is not executed as a part of the program.
• Comments can be used to:
• Let others understand your code
• Remind yourself of what you did
• Prevent blocks of code from being executed
• Syntax for comments in PHP code:
// This is a single-line comment
/* This is a
multi-line comment */
Comments in the Middle of the Code
<?php
$x = 5 /* + 15 */ + 5;
echo $x;
?>
Output:
10
PHP variables
• Variables are "containers" for storing information.
• Creating (Declaring) PHP Variables
• In PHP, a variable starts with the $ sign, followed by the name of the variable.
• A variable can have a short name (like $x and $y) or a more descriptive name ($age,
$total_volume)
• The assignment operator (=) used to assign value to a variable
• In PHP variable can be declared as : $variable_name=value;
• In PHP, there is no need to define data type of the variable
• PHP automatically associates a data type to the variable, depending on its value that’s why PHP is
a Loosely Typed Language
• Example:
<?php Output:
$x =5; // $x is an integer variable 5
$y =10.5; // $y is a float variable 10.5
$z ="Hello world!"; // $z is a string variable Hello world!
$a=$b="Fruit"; //Assign the same value to multiple variables in one line Fruit
echo $x ."<br>"; Fruit
echo $y ."<br>";
echo $z ."<br>";
echo $a ."<br>";
echo $b ."<br>";
?>
Rules for PHP variables
1. A variable starts with the $ sign, followed by the name of the variable
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
5. Variable names are case-sensitive ($age and $AGE are two different variables)
6. A variable name should not contain spaces. If a variable name is more than one
word, it should be separated with an underscore ($first_name), or with
capitalisation ($firstName).
• Remember that PHP variable names are case-sensitive !
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
• PHP has three different variable scopes:
• local
• global
• static
Local Scope
• A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function
• Example:
<?php
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
myTest();
echo "Variable x outside function is: $x";
?>
• Output:
Variable x inside function is:
Variable x outside function is: 5
PHP The global Keyword
• The global keyword is used to access a global variable within a function.
Example:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
Example:
<?php
function myTest()
{
static $x = 1;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
Output:
1
2
3
PHP Case Sensitivity
• PHP is partially case-sensitive, meaning that
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not
case-sensitive.
• However all variable names are case-sensitive "$color" and "$COLOR" would be considered different
variables in PHP
Example:
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
Output:
Hello World!
Hello World!
PHP Case Sensitivity
Example:
• The only the first statement will display the value of the $color variable.
• This is because $color, $COLOR, and $coLOR are treated as three different variables
<?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
PHP echo and print Statements
• With PHP, there are two basic ways to get output: echo and print.
• echo and print are more or less the same. They are both used to output data to the screen.
• The echo and print statement can be used with or without parentheses
• The differences are small:
Echo Print
Echo has no return value Print has a return value of 1, so it can be
used in expressions
Echo can take multiple parameters Print can take one parameter
Echo is marginally faster than print. Print is slower than echo
Syntax: echo($arg1,$arg2,…) Syntax: print ($arg)
Example: Example:
<?php <?php
echo "Hello world!<br>"; print "Hello world!<br>";
echo "This ", "string ", "was ", "made ", print "This string was made with single
"with multiple parameters."; parameter.";
?> ?>
PHP echo and print Statements
Example:
<?php
//The echo statement can be used with or without parentheses
echo ("Hello world <br>");
echo "Hello world <br>";
$txt1 = "W3Schools.com";
echo "Study PHP at $txt1 <br>"; //using double quotes, variables can be inserted to the string
echo 'Study PHP at ‘ . $txt1; // using single quotes, variables have to be inserted using the . operator
?>
Output:
Hello world
Hello world
Study PHP at W3Schools.com
Study PHP at W3Schools.com
PHP program that performs sum of two numbers
Example:
<?php
$x = 3;
$y = 2;
echo $x + $y;
?>
• Output:
5
How to output text and variables with the echo statements
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
Example:
<?php
$x = "Hello world!"; //string variable
$y = 'Hello world!';
Output:
string(12) "Hello world!"
string(12) "Hello world!"
PHP Integer
• An integer are whole numbers, without a decimal point, like 100.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:
• Example:
<?php
$x = 5985; //integer variable
var_dump($x); //returns the data type and value of variable
?>
• Output :
int(5985)
PHP Float
• A float (floating point number) is a number with a decimal point or a number like
3.14 or 49.1.
• In the following example $x is a float. The PHP var_dump() function returns the
data type and value:
• Example
<?php
$x = 10.365; //float variable
var_dump($x);
?>
• Output :
float(10.365)
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.
• Example:
<?php
$x = true;
var_dump($x);
?>
• Output:
bool(true)
PHP Array
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• If a variable is created without any value, then the NULL value is automatically assigned to it.
• Variables can also be emptied by setting the value to NULL:
• Example:
<?php
$x = "Hello world!";
$x = null;
$y;
var_dump($x);
echo "<br>";
var_dump($y);
?>
Output:
NULL
NULL
PHP Resource
• In PHP, Resource is a special data type that refers to any external resource.
• A resource variable acts as a reference to external source of data such as stream file,
database etc.
• PHP uses relevant functions to create these resources.
• For example, fopen() function opens a disk file and its reference is stored in a resource
variable
Example:
<?php
$fp=fopen("Test.txt","w");
var_dump($fp);
?>
Output:
resource(3) of type (stream)
PHP print_r() Function
• The print_r() function prints the information about a variable in a more human-readable way.
• Syntax: print_r($variable,$isStore)
• $ variable: Required parameter . Specifies the variable to be printed
• $isStore: Optional parameter. Its default value is false
• If this parameter is set to true, then the print_r function will store the output in a variable rather than
printing it.
• Example
<?php
$a = "hello world"; //string variable
$b = array("red", "green", "blue"); //array variable
$c = array("raj"=>"35", "yash"=>"37", "amit"=>"43");//array variable
print_r($a);
echo "<br>";
print_r($b);
echo "<br>";
print_r($c);
echo "<br>"; Output:
hello world
$d=print_r($a,true); // $isStore set to true Array ( [0] => red [1] => green [2] => blue )
print_r($d); Array ( [raj] => 35 [yash] => 37 [amit] => 43 )
?> hello world
PHP var_dump() Function
• The var_dump() function returns the data type and the value of variable
• Syntax: var_dump(var1, var2, ...);
• Example:
<?php
$a = 32;
$b = 32.5;
$c = "Hello world!"; Output:
$d = array("red", "green", "blue"); int(32)
float(32.5)
string(12) "Hello world!"
var_dump($a); array(3) { [0]=> string(3) "red" [1]=> string(5) "green"
echo "<br>"; [2]=> string(4) "blue" }
var_dump($b); int(32) float(32
echo "<br>";
var_dump($c);
echo"<br>";
var_dump($d);
echo"<br>";
var_dump($a, $b);// Dump two variables
?>
Type Juggling
• PHP is known as a dynamically typed language.
• In PHP data type of variable changes dynamically according to the value assigned to it. This feature is called "type juggling“.
• .
• Example:
<?php
$x = "Hello";//data type of $x is string
var_dump($x);
echo "<br>";
?>
Output:
string(5) "Hello"
int(10)
float(10.5)
Type Casting
• Typecasting is a process of converting a variable from one data type to another data type
• Typecasting is the explicit conversion of data type.
• A type can be cast by inserting one of the casts in front of the variable
• Casting in PHP is done with these statements:
•(string) - Converts to data type String
•(int) - Converts to data type Integer
•(float) - Converts to data type Float
•(bool) - Converts to data type Boolean
•(array) - Converts to data type Array
•(object) - Converts to data type Object
•(unset) - Converts to data type NULL
Type Casting
Example:
<pre>
<?php Output:
$a = 5; // Integer float(5)
$b = 5.34; // Float int(5)
$c = "hello"; // String string(5) "hello“
$d = true; // Boolean string(1) "1"
$e = NULL; // NULL string(0) ""
Note that when casting a Boolean into string it
$a = (float) $a; gets the value "1", and when casting NULL into
$b = (int) $b; string it is converted into an empty string "".
$c = (string)$c;
$d = (string)$d;
$e = (string)$e;
//To verify the type of any object in PHP, use the var_dump() function
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
Constants
• Constants in PHP are identifiers that are used to store fixed values and
• A constant value cannot change during the execution of the PHP script.
• Rules for constants:
• By default, a PHP constants are case-sensitive.
• By convention, constant identifiers are always uppercase.
• A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscore.
• There is no need to write a dollar sign ($) before a constant, however one can use a dollar sign before a constant.
• Creating a Constant using define() function:
Example:
<?php
define("WELCOME", "GeeksforGeeks");//creates a case-sensitive constant
echo WELCOME . "<br>";
• The PHP arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
PHP Arithmetic Operators
Example:
<?php
echo "Arithmetic Operators:";
$x = 5;
$y = 2;
echo("<br> Addition is:".($x + $y));
echo("<br> subtraction is:".($x- $y));
echo("<br> Multiplication is:".($x* $y));
echo("<br> Division is:".($x / $y));
echo("<br> Modulus is:".($x % $y));
echo("<br> Exponentiation is:".($x ** $y));
?>
Output:
Arithmetic Operators:
Addition is:7
subtraction is:3
Multiplication is:10
Division is:2.5
Modulus is:1
PHP Assignment operators
Operator Name Example Same as... Result
Assigns value of right operand to the
= Assign $x = $y $x = $y
left operand
• The PHP comparison operators are used to compare two values (number or string) or operands
PHP Comparison Operators
Example:
<?php
echo "Comparison Operators";
$x=10; Output:
$y=20;
echo "<br>"; Comparison Operators
var_dump($x==$y);//equal to operator
bool(false)
echo "<br>"; bool(true)
var_dump($x!=$y);//not equal to operator (<>) bool(false)
bool(true)
echo "<br>";
var_dump($x===$y);//identical operator
bool(true)
bool(true)
echo "<br>"; bool(false)
var_dump($x!==$y);//not identical operator bool(false)
echo "<br>";
var_dump($x<$y);//less than operator
echo "<br>";
var_dump($x<=$y);//less than or equal to operator
echo "<br>";
var_dump($x>$y);//greater than operator
echo "<br>";
var_dump($x>=$y);//greater than or equal to operator
?>
PHP Comparison Operators
Example:
<?php
echo "Spaceship Operators";
$x = 10;
$y = 10;
echo("<br>".($x <=> $y)); // returns 0 because $x and $y values are equal
$x = 15;
$y = 10;
echo("<br>".($x <=> $y)); // returns 1 because $x is greater than $y
$x = 5;
$y = 10;
echo("<br>".($x <=> $y)); // returns -1 because $x is less than $y
?>
Output:
Spaceship Operators
0
1
-1
PHP Increment / Decrement Operators
• Increment / Decrement Operators are called the Unary operators as they works on single
operand
PHP Increment / Decrement Operators
Example:
<?php
echo "Increment / Decrement Operators"; Output:
$x=3; Increment / Decrement Operators
echo ("<br> first increments then prints:".++$x); first increments then prints:4
first prints then increments:3
$x=3; first decrements then prints:2
echo ("<br> first prints then increments:".$x++); first prints then decrements:3
$x=3;
echo ("<br> first decrements then prints:".--$x);
$x=3;
echo ("<br> first prints then decrements:".$x--);
?>
PHP Logical Operators
Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
• The PHP logical operators are used to combine multiple conditions into single
condition
PHP Logical Operators
Example:
<?php Output:
echo "Logical Operators"; Logical Operators
$x=10; True
$y=20; True
if ($x==10 and $y==20) //logical AND(&&) False
echo ("<br> True"); False
else
echo (" <br> False");
Example:
<?php
echo "String Operators"; Output:
$x="Hello"; String Operators
$y="World!"; HelloWorld!
HelloWorld!
$z=$x.$y;
echo ("<br>".$z);
$x.=$y;
echo ("<br>".$x);
?>
PHP Array Operators
Operator Name Example Result
echo "<br>";
var_dump($x != $y); //inequality operator
echo "<br>";
var_dump($x <> $y);//inequality operator
echo "<br>";
var_dump($x === $y);//identity operator
echo "<br>";
var_dump($x !== $y);//non-identity operator
?>
PHP Conditional Assignment Operators
Operator Name Example Result
Returns the value of $x.
?: Ternary $x = expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
Returns the value of $x.
The value of $x is expr1 if expr1 exists, and
Null is not NULL.
?? $x = expr1 ?? expr2
coalescing If expr1 does not exist, or is NULL, the value
of $x is expr2.
Introduced in PHP 7
• The PHP conditional assignment operators are used to assign a value to variable depending on
conditions
Ternary operator
• The ternary operator (?:) is a conditional operator used to evaluate the condition, if condition is
true then statement 1 is executed and if condition is false then statement 2 is executed.
• It is called a ternary operator because it takes three operands- a condition, a result statement for
true, and a result statement for false.
• The use of the ternary operator will make the code shorter as compared with IF ELSE statement.
• Syntax:
Variable = (Condition) ? (Statement1) : (Statement2);
• Example:
<?php
$age = 10;
$x= ($age >= 18) ? "Adult" : "Not Adult";
echo $x;
?>
• Output:
Not Adult
Null Coalescing Operator
• Syntax:
$Var = $operand1 ?? $operand2;
• Example:
<?php
$x=null;
$y="green";
$color = $x ?? $y;
echo "The color is: ".$color;
?>
Output:
The color is: green
PHP Bitwise Operators
Operator Name Example Description
It returns 1 , only if both the bits are 1; otherwise it
& Bitwise AND $x & $y returns 0
Bitwise Left It shifts the bits of left operand towards the left by
<< $x << $y
Shift the number of bits given in the right operand.
Bitwise Right It shifts the bits of left operand towards the right by
>> $x >>$y
Shift the number of bits given in right operand.
• Bitwise Operator operates on binary digits that are used to perform bit level operations
on the operands
PHP Bitwise Operators
Example:
<?php
echo "Bitwise Operators"; Bitwise Operators
$x=5; Bitwise AND: 1
$y=1; Bitwise OR: 5
Bitwise XOR: 4
echo("<br>Bitwise AND: ". ($x & $y)); Bitwise NOT: -6
Bitwise Left Shift: 10
echo("<br>Bitwise OR: ".($x|$y)); Bitwise Right Shift: 2
echo("<br>Bitwise XOR: ".($x^$y));
• If Statement
• If-else Statement
• If-elseif-else Statement
• Nested if Statement
• Switch Statement
• Break Statement
• Continue Statement
If Statement
• If statement is used to executes the block of code only if the specified condition evaluates to true.
• Syntax
if(condition)
{
//code to be executed if condition is true
}
• Example:
<?php
$a=10;
if($a==10)
{
echo (“ The number is:".$a);
}
?>
Output:
number is:10
If-else Statement
• The if...else statement executes some code if a condition is true and another code if that condition
is false.
• Syntax
if (condition)
{ // code to be executed if condition is true;
}
else
{ // code to be executed if condition is false;
}
• Example:
<?php
$a=10;
if($a>0)
{ echo ("number is positive");
}
else
{ echo ("number is negative");
}
?>
If-else Statement
• Output:
12 is even number
If-elseif-else Statement
• The if...elseif...else statement executes different codes for more than two conditions.
• Syntax
if (condition1)
{ //code to be executed if condition1 is true;
}
elseif (condition2)
{ // code to be executed if condition1 is false and condition2 is true;
}
else
{ // code to be executed if all conditions are false;
}
If-elseif-else Statement
• Example:
<?php
$per=75;
if($per>=75)
{ echo "Distinction";
}
elseif($per>=60 and $per<75)
{ echo "First Class";
}
elseif($per>=50 and $per<60)
{ echo "Second Class";
}
elseif($per>=40 and $per<50)
{ echo "Pass Class";
}
else
{echo "Fail";
}
?>
Nested If statement
• The if statements inside another if statement is called nested if statements. or
• The nested if statement consists the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.
• Syntax
if (condition1)
{ //code to be executed if condition1 is true
if (condition2)
{
//code to be executed if both condition1 and condition2 are true
}
}
Nested If statement
• Example:
<?php
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
• Output:
• Above 10 but not above 20
Switch statement
• The switch statement is used to perform different actions based on different conditions. or
The switch statement is used to select one of many blocks of code to be executed.
• This is how it works:
• The expression is evaluated once.
• The value of the expression is then compared with the values of each case.
• If there is a match, the block of code associated with that case is executed.
• The default code block is executed if there is no match.
• The break keyword breaks out of the switch block.
• Syntax
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// additional cases as needed
default:
// Code to be executed if none of the cases match the expression
break;
Switch statement
Example:
<?php
$a=10;
$b=20;
$ch=3;
switch ($ch) {
case 1:
echo "Addition=".($a+$b);
break;
case 2:
echo "Substraction=".($a-$b);
break;
case 3:
echo "Multiplication=".($a*$b);
break;
case 4:
echo "Division=".($a/$b);
break;
case 5:
echo "Modulus=".($a%$b);
break;
case 6:
echo "Exponentiation=".($a**$b);
break;
default:
echo "Wrong Choice";
break;
}
?>
Output : Multiplication=200
Switch statement
Example:
<?php
$per = 75;
switch (true) {
case ($per >=75):
echo "Distinction";
break;
case ($per >=60 and $per < 75):
echo "First Class";
break;
case ($per >=50 and $per < 60):
echo "Second Class";
break;
case ($per >=40 and $per < 50):
echo "Pass Class";
break;
default:
echo "Fail";
break;
}
?>
Output : Distinction
Switch statement
Example:
<?php
$var = date("D");
echo $var;
switch ($var) {
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
default:
echo "It is the weekend!";
break;
}
?>
Output :
Break statement
• The break statement is used to jump out of different kind of loops. Or its used to exit from loops
• When break statement is executed inside loop then it terminate the execution of current loop and transfer the control
to the next statement outside the loop.
• A break is usually associated with the if statement
• Syntax:
if (condition)
{
//code to be executed if condition is true
break;
} Output:
• Example: Jump out of the loop when $i is 4 0
1
<?php 2
echo "Output:<br>"; 3
for ($i = 0; $i< 10; $i++)
{
if ($i ==4)
{ break; //Terminate the loop if condition is true.
}
echo "$i <br>";
}
Continue Statement
• The continue statement used to skip the execution of the current iteration in the loop and
continue with the next iteration
• Syntax:
if (condition)
{ //code to be executed if condition is true
continue;
}
Output:
• Example: Move to next iteration if $i = 4
0
1
<?php
2
echo "Output:<br>"; 3
for ($i = 0; $i< 10; $i++) 5
6
{
7
if ($i == 4) 8
{ continue; 9
}
echo $i. "<br>";
}
?>
Loop Control Statements
• Loops are used to execute the same block of code again and again, as long as
a certain condition is true.
• While Loop
• do-while loop
• For Loop
• foreach loop
While Loop
• The while loop executes a block of code as long as the specified condition is true.
• Syntax:
while(condition){
//code to be executed
}
While Loop
• Example: PHP program to display numbers from 1to 10 using while Loop
<?php
$n=1;
while($n<=10){
echo "$n <br>";
$n++;
}
?>
• Output:
1
2
3
4
5
6
7
8
9
10
Do-While Loop
• The do...while loop will execute the block of code at least once, then it will
check the condition, and repeatedly executes the block of code as long as the
specified condition is true.
• do...while loop will execute the block of code at least once, even if the condition
is false
• Syntax
do{
//code to be executed
}while(condition);
Do-While Loop
• Example: PHP program to display numbers from 1to 10 using do-while loop
<?php
$n=1;
do{
echo "$n <br>";
$n++;
}while($n<=10)
?>
Output:
1
2
3
4
5
6
7
8
9
10
For Loop
• PHP for loop can be used to traverse set of code for the specified number of times.
• The for loop is used to execute a block of code repeatedly, specified number of times.
• for loop is used when you already know how many times you want to execute a block of code.
• Syntax
for(initialization; condition; increment/decrement){
//code to be executed
}
For Loop
• Example: PHP program to display numbers from 1-10 in a sequence using for loop.
<?php
for ($n = 1; $n <= 10; $n++){
echo "The number is: $n<br>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
For Loop
Example: PHP program to display even numbers from 1-50 (using for ,while and do..while loop.
<?php
echo "Even numbers from 1-50 using for loop<br>"; Output:
Even numbers from 1-50 using for loop
for ($i = 1; $i <=50; $i++) { 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
if ($i % 2 == 0) 40 42 44 46 48 50
echo " ".$i;
} Even numbers from 1-50 using while loop
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
40 42 44 46 48 50
echo "<br><br>Even numbers from 1-50 using while loop<br>";
$i = 1; Even numbers from 1-50 using do-while loop
while ($i <= 50) { 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
40 42 44 46 48 50
if ($i % 2 == 0)
echo " ".$i;
$i++;
}
• Syntax1:
foreach ($array_var as $value)
{ //code to be executed
}
• Syntax2:
foreach ($array_var as $key=>$value)
{ //code to be executed
}
Foreach Loop
Example: PHP program to print elements of array using foreach loop or
Loop through the items of an indexed array
<?php
//declare an indexed array
$student=array("raj","ram","sagar");
Example: PHP program to print both the key and the value pairs from an associative array or
Loop through the items of an associative array
<?php
//declare an associative array
$student= array("name"=>"raj","age"=>25 , "email"=>"raj123@gmail.com");
//access elements of array using foreach loop
foreach ($student as $key => $value) {
echo "$key : $value <br>";
}
?>
Output:
name : raj
age : 25
email : raj123@gmail.com