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

php unit 1

The document provides a comprehensive overview of variables in PHP, including their declaration, rules, types, and scopes. It explains local, global, and static variables, as well as constants and data types supported by PHP. Additionally, it covers the differences between constants and variables, and details the various scalar, compound, and special data types available in PHP.

Uploaded by

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

php unit 1

The document provides a comprehensive overview of variables in PHP, including their declaration, rules, types, and scopes. It explains local, global, and static variables, as well as constants and data types supported by PHP. Additionally, it covers the differences between constants and variables, and details the various scalar, compound, and special data types available in PHP.

Uploaded by

sreeee437
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Variables

A variable is a data name that may be used to store a data vale. 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, we do not need to declare the


data types of the variables. It automatically converts the variable to
its correct data type.
 After declaring a variable, it can be reused throughout the code.
 Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:


$variablename = value;

Rules for declaring a variable:


o A variable must start with a dollar ($) sign, followed by the variable
name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character. A
variable name cannot start with a number or special symbols.
o A PHP variable name cannot contain spaces.
o 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.

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:

string is: hello string


integer is: 200
float is: 44.6

variable2.php

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

Output:

11

In PHP, variable names are case sensitive. So variable name "color" is different
from Color, COLOR, COLor etc.

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
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

variablevalid.php

<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)

echo "$a <br> $_b";


?>

Output:

hello
hello

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:
 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.
local_variable1.php
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Local variable declared inside the function is: 45

local_variable2.php
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
//using $lang (local variable) outside the function will generate an error
echo $lang;
?>
Output:
Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line
28

Global variable
The global variables are the variables that are declared outside the function.
These variables can be accessed anywhere in the program. There is no need to
use any keyword to access a global variable outside the function. To access the
global variable within a function, use the GLOBAL keyword before the variable.
Example:
global_variable1.php
<?php
$name = "Sanaya Sharma"; //Global Variable
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
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.
Example:
global_variable2.php
<?php
$name = "Sanaya Sharma"; //global variable
function global_var()
{
echo "Variable inside the function: ". $name;
echo "<br>";
}
global_var();
?>
Output:
Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line
6
Variable inside the function:
Using $GLOBALS instead of global
Another way to use the global variable inside the function is predefined
$GLOBALS array.
Example:
global_variable3.php
<?php
$num1 = 5; //global variable
$num2 = 13; //global variable
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:
global_variable2.php
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Output:
Value of x: 7

Static variable

Normally, when a function is completed/executed, all of its variables are


deleted from memory. However, sometimes we want a local variable NOT to be
deleted. To do this, use the static keyword when you first declare the variable.
Static variables exist only in a local function, but it does not free its memory
after the program execution leaves the scope.
Example:
static_variable.php
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
$num1++; //increment in non-static variable
$num2++; //increment in static variable
echo "Static: " .$num1 ."<br>";
echo "Non-static: " .$num2 ."<br>";
}
//first function call
static_var();
//second function call
static_var();
?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
$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.

Constants
PHP constants are name or identifier that can't be changed during the
execution of the script. They remain constant across the entire program. PHP
constants follow the same PHP variable rules. For example, it can be started
with a letter or underscore only.
Conventionally, PHP constants should be defined in uppercase letters. Unlike
variables, constants are automatically global throughout the script. PHP
constants can be defined by 2 ways:
 Using define() function
 Using const keyword
define()
The define() function is used 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);

 name: It specifies the constant name.


 value: It specifies the constant value.
 case-insensitive: Specifies whether a constant is case-insensitive.
Default value is false. It means it is case sensitive by default.

constant1.php

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

Output:

Hello JavaTpoint PHP

Create a constant with case-insensitive name:

constant2.php

<?php
define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
echo MESSAGE, "<br>";
echo message;
?>
Output:
Hello JavaTpoint PHP
Hello JavaTpoint PHP

constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

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.

File: constant4.php

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

Output:

Hello const by JavaTpoint PHP

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)

File: constant5.php

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

Output:

JavaTpoint
JavaTpoint

Constant vs Variables

Constant Variables

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

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

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

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

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

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

Data Types

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

Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

 integer
 float
 string
 boolean

Integer

Integer means numeric data with a negative or positive sign. It holds only
whole numbers, i.e., numbers without fractional part or decimal point.

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:

<?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
Octal number: 163
HexaDecimal number: 69

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. Float and integer are numeric data types.

Example:

<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

Output:

Addition of floating numbers: 73.812

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

Hello Javatpoint
Hello $company

Boolean

Booleans are the simplest data type. 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 returns FALSE.

Example:

<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>

Output:

This condition is TRUE.

Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

 array
 object

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);
//the var_dump() function returns the datatype and values
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" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

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:

Bike Model: Royal Enfield


Special Types

There are 2 special data types in PHP.

 resource
 NULL

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.

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; //it will not give any output
?>

Output:

 gettype() operator, is used for finding out the type of a particular


variable.
 var_dump() function tells what a variable contains, it also shows the
variable’s data type.
<?php
$whoami = 'Sarah'; // define string variable
echo gettype($whoami); // gettype() returns the type of a variable. // output:
'string'
$whoami = 99.8; // assign new value to variable
echo gettype($whoami); // output: 'double'
$x = 25;
var_dump($x); // var_dump() returns the datatype and values //
output int(25)
unset($whoami); // destroy variable
echo gettype($whoami); // output: 'NULL'
?>

It’s possible to explicitly set the type of a variable by casting a variable to a


specific type before using it. Casting is a technique commonly used by
programmers. To use it, simply specify the desired data type in parentheses on
the right side of the assignment equation.
Consider the following example, which illustrates turning a floating-point value
into an integer value:
<?php
// define floating-point variable
$speed = 501.789;
// cast to integer
$newSpeed = (integer) $speed;
// output: 501
echo $newSpeed;
?>
PHP includes a number of more specialized functions, to test if a variable is of a
specific type.
Functions to Test Variable’s Data Types
Function Purpose
is_bool() Tests if a variable holds a Boolean value
is_numeric() Tests if a variable holds a numeric value
is_int() Tests if a variable holds an integer
is_float() Tests if a variable holds a floating-point value
is_string() Tests if a variable holds a string value
is_null() Tests if a variable holds a NULL value
is_array() Tests if a variable is an array
is object() Tests if a variable is an object

Operators
Operator is a symbol that is used to perform operations on operands. In
simple words, operators are used to perform operations on variables or values.
PHP Operators can be categorized in following forms:

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

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


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

Arithmetic Operators

The arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.

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

The exponentiation (**) operator has been introduced in PHP 5.6.

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 $a -= $b Subtraction same as $a = $a - $b


Assign

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


Assign

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


Assign
(quotient)

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


Assign
(remainder)

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 $a | $b Bits that are 1 in either $a or $b are set to 1


or)

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


or)

~ 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 strings. 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 === Return TRUE if $a is equal to $b, and they


$b 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

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


equal to

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


equal 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 $a 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

String Operators

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

Operator Name Exampl Explanation


e

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

.= Concatenation and $a .= $b First concatenate $a and $b, then assign


Assignment the concatenated string to $a, e.g. $a = $a
. $b

Array Operators

The array operators are used in 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 === Return TRUE if $a and $b have same key/value pair
$b 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

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.

1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "<br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22.?>
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.

Operator Name Example Explanation

`` backtick echo Execute the shell command and return the result.
s `dir`; Here, it will show the directories available in current
folder.

Error Control Operators

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.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

Precedence of operators with associativity:

Operators Additional Information Associativity


clone new clone and new non-
associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) increment/decrement and right


(object) (bool) @ types

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left


|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= assignment right


>>= =>

and logical left

xor logical left

or logical left

, many uses (comma) left

Arrays

What is an Array?

An array is a special variable that can hold many values under a single name,
and you can access the values by referring to an index number or name.

Array Types

In PHP, there are three types of arrays:

 Indexed arrays / Numeric arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
Create Array

You can create arrays by using the array() function:

$cars = array("Volvo", "BMW", "Toyota");

You can also use a shorter syntax by using the [] brackets:

$cars = ["Volvo", "BMW", "Toyota"];

Line breaks are not important, so an array declaration can span multiple lines:

$cars = [

"Volvo",

"BMW",

"Toyota"

];

A comma after the last item is allowed:

$cars = [

"Volvo",

"BMW",

"Toyota",

];

Array Keys
When creating indexed arrays the keys are given automatically, starting at 0
and increased by 1 for each item, so the array above could also be created with
keys:

$cars = [

0 => "Volvo",

1 => "BMW",

2 =>"Toyota"

];

Indexed arrays are the same as associative arrays, but associative arrays have
names instead of numbers:

$myCar = [

"brand" => "Ford",

"model" => "Mustang",

"year" => 1964

];

You can declare an empty array first, and add items to it later:

$cars = [];

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";

The same goes for associative arrays, you can declare the array first, and then
add items to it:

$myCar = [];

$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";

$myCar["year"] = 1964;

Mixing Array Keys

You can have arrays with both indexed and named keys:

$myArr = [];

$myArr[0] = "apples";

$myArr[1] = "bananas";

$myArr["fruit"] = "cherries";

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.

Access an item by referring to its index number:

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[2];

Note: The first item has index 0.

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

Access an item by referring to its key name:

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

echo $cars["year"];

Update Array Item

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

Change the second array item from "BMW" to "Ford":


$cars = array("Volvo", "BMW", "Toyota");

$cars[1] = "Ford";

Note: The first item has index 0.

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

Update the year to 2024:

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

$cars["year"] = 2024;

Remove Array Item

To remove an existing item from an array, you can use the unset() function.

The unset() function deletes specified variables, and can therefore be used to
delete array items:

Remove the second item:

$cars = array("Volvo", "BMW", "Toyota");

unset($cars[1]);

Remove Multiple Array Items

The unset() function takes a unlimited number of arguments, and can


therefore be used to delete multiple array items:

Remove the first and the second item:

$cars = array("Volvo", "BMW", "Toyota");

unset($cars[0], $cars[1]);

Indexed Arrays

In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.
Create and display an indexed array:

$cars = array("Volvo", "BMW", "Toyota");

var_dump($cars);

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Access Indexed Arrays

To access an array item you can refer to the index number.

Display the first array item:

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[0];

Volvo
Change Value

To change the value of an array item, use the index number:

Change the value of the second item:

$cars = array("Volvo", "BMW", "Toyota");

$cars[1] = "Ford";

var_dump($cars);

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}

Access Associative Arrays

To access an array item you can refer to the key name.

Display the model of the car:

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

echo $car["model"];

Mustang

Change Value

To change the value of an array item, use the key name:

Example

Change the year item:

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

$car["year"] = 2024;

var_dump($car);
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}

Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage.

The dimension of an array indicates the number of indices you need to select
an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an
element

Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an


array of arrays of arrays).

First, take a look at the following table:

Name Stock Sold

Volvo 22 18

BMW 15 13
Saab 5 2

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like
this:

$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.

To get access to the elements of the $cars array we must point to the two
indices (row and column):

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15

Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order,


descending or ascending.

Sort Functions for Arrays

PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the
value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending
alphabetical order:

$cars = array("Volvo", "BMW", "Toyota");

sort($cars);

BMW
Toyota
Volvo

The following example sorts the elements of the $numbers array in ascending
numerical order:
$numbers = array(4, 6, 2, 22, 11);

sort($numbers);

2
4
6
11
22

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending
alphabetical order:

$cars = array("Volvo", "BMW", "Toyota");

rsort($cars);

Volvo
Toyota
BMW

The following example sorts the elements of the $numbers array in descending
numerical order:

$numbers = array(4, 6, 2, 22, 11);

rsort($numbers);

Sort Array (Ascending Order), According to Value - asort()

The following example sorts an associative array in ascending order, according


to the value:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

asort($age);
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

Sort Array (Ascending Order), According to Key - ksort()

The following example sorts an associative array in ascending order, according


to the key:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

ksort($age);

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

Sort Array (Descending Order), According to Value - arsort()

The following example sorts an associative array in descending order,


according to the value:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

arsort($age);

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

Sort Array (Descending Order), According to Key - krsort()

The following example sorts an associative array in descending order,


according to the key:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


krsort($age);

Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
Retrieving Array Size
An important task when using arrays, especially in combination with loops, is
finding out how many values the array contains. This is easily accomplished
with PHP’s count() function, which accepts the array variable as a parameter
and returns an integer value indicating how many elements it contains. Here’s
an example:
<?php
// define array
$data = array('Monday', 'Tuesday', 'Wednesday');
// get array size
echo 'The array has ' . count($data) . ' elements';
?>
3

Instead of the count() function, you can also use the sizeof() function, which
does the same thing.

Array Functions

PHP has a set of built-in functions that you can use on arrays. Function

explode() Splits a string into array elements

implode() Joins array elements into a string

range() Generates a number range as an array

min() Finds the smallest value in an array

max() Finds the largest value in an array


shuffle() Randomly rearranges the sequence of elements in an array

array_slice() Extracts a segment of an array

array_shift() Removes an element from the beginning of an array

array_unshift() Adds an element to the beginning of an array

array_pop() Removes an element from the end of an array

array_push() Adds an element to the end of an array

array_unique() Removes duplicate elements from an array

array_reverse() Reverses the sequence of elements in an array

array_merge() Combines two or more arrays

array_intersect() Calculates the common elements between two or more


arrays

array_diff() Calculates the difference between two arrays

in_array() Checks if a particular value exists in an array

array_key_exists() Checks if a particular key exists in an array

sort() Sorts an array

asort() Sorts an associative array by value

ksort() Sorts an associative array by key

rsort() Reverse-sorts an array

krsort() Reverse-sorts an associative array by value

arsort() Reverse-sorts an associative array by key

Common PHP Array Functions


Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input array

array_combine() Creates an array by using the elements from one "keys" array a
"values" array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values o

array_diff_assoc() Compare arrays, and returns the differences (compare keys and

array_diff_key() Compare arrays, and returns the differences (compare keys onl

array_diff_uassoc() Compare arrays, and returns the differences (compare keys and
using a user-defined key comparison function)

array_diff_ukey() Compare arrays, and returns the differences (compare keys onl
user-defined key comparison function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only

array_intersect_assoc() Compare arrays and returns the matches (compare keys and va

array_intersect_key() Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and v
a user-defined key comparison function)

array_intersect_ukey() Compare arrays, and returns the matches (compare keys only,
defined key comparison function)

array_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array

array_map() Sends each value of an array to a user-made function, which re


values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified value, to a

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array


array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined function

array_replace() Replaces the values of the first array with the values from follo

array_replace_recursive() Replaces the values of the first array with the values from follo
recursively

array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the key

array_shift() Removes the first element from an array, and returns the value
removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array

array_udiff() Compare arrays, and returns the differences (compare values o


user-defined key comparison function)

array_udiff_assoc() Compare arrays, and returns the differences (compare keys and
using a built-in function to compare the keys and a user-define
to compare the values)

array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and
using two user-defined key comparison functions)

array_uintersect() Compare arrays, and returns the matches (compare values only
user-defined key comparison function)

array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and v
a built-in function to compare the keys and a user-defined func
compare the values)

array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and v
two user-defined key comparison functions)

array_unique() Removes duplicate values from an array

array_unshift() Adds one or more elements to the beginning of an array

array_values() Returns all the values of an array


array_walk() Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an arra

arsort() Sorts an associative array in descending order, according to the

asort() Sorts an associative array in ascending order, according to the v

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

each() Deprecated from PHP 7.2. Returns the current key and value pa
array

end() Sets the internal pointer of an array to its last element

extract() Imports variables into the current symbol table from an array

in_array() Checks if a specified value exists in an array


key() Fetches a key from an array

krsort() Sorts an associative array in descending order, according to the

ksort() Sorts an associative array in ascending order, according to the k

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order" algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements

reset() Sets the internal pointer of an array to its first element


rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined comparison functi


maintains the index association

uksort() Sorts an array by keys using a user-defined comparison functio

usort() Sorts an array by values using a user-defined comparison functi

Conditional Statements

Conditional statements are used to perform different actions based on


different conditions.

In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and
another code if that condition is false
 if...elseif...else statement - executes different codes for more than two
conditions
 switch statement - selects one of many blocks of code to be executed

if Statement

This statement executes the block of code inside the if statement if the
expression is evaluated as True.

Syntax

if (condition) {

// code to be executed if condition is true;

Flowchart

Example:
<?php
$x = 12;

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

if...else Statement
This statement executes the block of code inside the if statement if the
expression is evaluated as True and executes the block of code inside
the else statement if the expression is evaluated as False.

Syntax

if (condition) {

// code to be executed if condition is true;

} else {

// code to be executed if condition is false;

Flowchart
Example:

<?php
$x = -12;

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

else{
echo "The number is negative";
}
?>

Output:
The number is negative

If-else-if-else
This statement executes different expressions for more than two
conditions.

Syntax

if (condition) {

code to be executed if this condition is true;

} elseif (condition) {

// code to be executed if first condition is false and this condition is true;

} else {

// code to be executed if all conditions are false;

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

Nested if Statement

if statements inside if statements is called nested if statements.

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

switch Statement

The switch statement is used to perform different actions based on


different conditions. Use the switch statement to select one of many
blocks of code to be executed. Rather than using if-elseif-if, we can use
the switch statement to make our program.
Syntax

switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
}

This is how it works:


 The expression is evaluated once
 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break keyword breaks out of the switch block
 The default code block is executed if there is no match

Flowchart:
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":
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<?php

<?php
$i = "2";
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>

Output:
i equals 2
Loops

Loops are used to execute a statement or a block of statements,


multiple times as long as a certain condition is true.

The loop structure includes three sections. These are,

 Initialization – To initialize the first iteration index of the


loop.
 Conditional execution – For each iteration, it checks whether
the specified condition is satisfied. If so, then only the code
will be executed.
 Incrementation/decrementation – After processing each
iteration, the loop index should be incremented or
decremented to process the next iteration. This will be
continued till the loop condition is satisfied.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition


is true
 do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

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:

Syntax

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


2. //code to be executed
3. }

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

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

Output:

5
6

10

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.

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

Output:

PHP Nested For Loop

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

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

Output:

11

12
13

21

22

23

31

32

33

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

Example 2:
PHP program to print associative array elements using foreach loop.

1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "[email protected]",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>

Output:

Name : Alex
Email : [email protected]
Age : 21
Gender : Male

Example 3:
Multi-dimensional array

1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
5. $a[0][1] = "Bob";
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {
12. echo "$e2\n";
13. }
14. }
15. ?>

Output:

Alex Bob Camila Denial

Example 4:
Dynamic array

1. <?php
2. //dynamic array
3. foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
4. echo "$elements\n";
5. }
6. ?>

Output:

j a v a t p o i n t

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 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 Nested While Loop


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
1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>
Output:
11
12
13
21
22
23
31
32
33

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.
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. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as entry The do-while loop is also named as exit
control loop. control loop.

The body of the loop does not execute The body of the loop executes at least once,
if the condition is false. even if the condition is false.

Condition checks first, and then block Block of statements executes first and then
of statements executes. condition checks.

This loop does not use a semicolon to Do-while loop use semicolon to terminate the
terminate the loop. loop.

most popular way to access items in array in php is using


loops : while, for & do..while
array using while loop

Here, we will create an index position variable and start


with 0th position which is first in an array.

The condition will be to continue fetching element from an


array til our index values is less than the count of array (or
length of the given array).
Since, while loop will not increment our index variable automatically, we
need to increment it inside the loop. Therefore, with each iteration, variable
will move to next index position.
<?php
$users = ['john', 'dave', 'tim'];

$i = 0;

while($i < count($users))


{
echo $users[$i]."\n";
$i++;
}
?>
Output:
john
dave
tim
array using do while loop
We will iterate over an array of users using do while loop.
Example:
<?php
$users = ['john', 'dave', 'tim'];

$i = 0;

do
{
echo $users[$i]."\n";
$i++;
}
while($i < count($users));
?>
Output:
john
dave
tim
array using for loop in PHP
As shown below, it is exactly same as while loop, except it's condensed and
better syntax. Also, for one line statements, you can omit curly brackets ;)
<?php
$users = ['john', 'dave', 'tim'];

for($i = 0;$i < count($users);$i++)


echo $users[$i]."\n";
?>
Output:
john
dave
tim
array using foreach loop in PHP
Let's recreate our example. We won't need the keys (position) therefore we
will use foreach without keys.
<?php

$users = ['john', 'dave', 'tim'];

foreach($users as $user)
echo $user."\n";
?>
Output:
john
dave
tim

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.

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
1. jump statement;
2. break;
Flowchart

PHP Break: inside loop


1. Let's see a simple example to break the execution of for loop if value of
i is equal to 5. <?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
5
P

PHP Break: inside inner loop


The PHP break statement breaks the execution of inner loop only.
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>
Output:
11
12
13
21
22
31
32
33
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:
1. jump-statement;
2. 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

You might also like