Unit 2 (php)
Unit 2 (php)
1. if Statement
This statement executes the block of code inside the if statement if the
expression is evaluated as True.
Example:
<?php
$x = "22";
if ($x < "20") {
echo "Hello World!";
}
?>
Copy
2. 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.
Example:
<?php
$x = "22";
if ($x < "20") {
echo "Less than 20";
} else {
echo "Greater than 20";
}
?>
Copy
3. If-else-if-else
This statement executes different expressions for more than two conditions.
Example:
<?php
$x = "22";
if ($x == "22") {
echo "correct guess";
} else if ($x < "22") {
echo "Less than 22";
} else {
echo "Greater than 22";
}
?>
Copy
4. Switch Statement
This statement allows us to execute different blocks of code based on different
conditions. Rather than using if-elseif-if, we can use the switch statement to
make our program.
Example:
<?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";
}
?>
t
o
b
e
e
x
e
c
u
t
e
d
}
Example-
1
<
2
?
3
p
4
h
5
p
6
$
7
i
8
=
0
;
w
h
i
l
e
(
$
i
<
=
1
0
)
{
/
/
o
u
t
p
u
t
v
a
l
u
e
f
r
o
m
1
0
e
c
h
o
"
T
h
e
N
u
m
b
e
r
i
s
"
.
$
i
.
"
<
b
r
>
"
;
$
i
+
+
;
}
?
>
Output-
The Number is 0
The Number is 1
The Number is 2
The Number is 3
The Number is 4
The Number is 5
The Number is 6
The Number is 7
The Number is 8
The Number is 9
The Number is 10
The Do While Loop
Do while statement is same as the while statement, the only difference is that it
evaluates the expression at the end.
Syntax –
1
d
2
o
3
{
4
c
5
o
d
e
t
o
b
e
e
x
e
c
u
t
e
d
}
w
h
i
l
e
(
c
o
n
d
i
t
i
o
n
)
;
Example –
1
<
2
?
3
p
4
h
5
p
6
$
7
i
8
=
9
0
;
d
o
{
/
/
o
u
t
p
u
t
v
a
l
u
e
0
f
r
o
m
1
0
e
c
h
o
"
T
h
e
N
u
m
b
e
r
i
s
"
.
$
i
.
"
<
b
r
>
"
;
$
i
+
+
;
}
w
h
i
l
e
(
$
i
<
=
1
0
)
?
>
Output-
The Number is 0
The Number is 1
The Number is 2
The Number is 3
The Number is 4
The Number is 5
The Number is 6
The Number is 7
The Number is 8
The Number is 9
The Number is 10
The For Loop
The for loop is used when you know in advance how many times the script
should run.
Syntax-
1
f
2
o
3
r
4
(
i
n
i
t
i
a
l
i
z
a
t
i
o
n
;
c
o
n
d
i
t
i
o
n
;
i
n
c
r
e
m
e
n
t
)
{
c
o
d
e
t
o
b
e
e
x
e
c
u
t
e
d
}
The for loop statement take three expressions inside its parenthesis. Separated
by semi-colons. When the for loop executes, the following occurs –
The initialization expression is executed. This expression usually initializes
one or more loop counter, but the syntax allows an expression of any
degree of complexity.
The Condition expression is evaluated. If the value of condition is true, the
loop statement execute. If the value of condition is false, the for loop
terminates.
The update expression increment executes.
The statement executes, and control return to step 2.
Example –
1
<
2
?
3
p
4
h
5
p
6
f
o
r
(
$
i
=
0
;
$
i
<
=
1
0
;
$
i
+
+
)
{
e
c
h
o
"
T
h
e
N
u
m
b
e
r
i
s
"
.
$
i
.
"
<
b
r
/
>
"
;
}
?
>
Output-
The Number is 0
The Number is 1
The Number is 2
The Number is 3
The Number is 4
The Number is 5
The Number is 6
The Number is 7
The Number is 8
The Number is 9
The Number is 10
The Foreach Loop
For Each structure is a loop structure used for arrays.
Syntax –
1
f
2
o
3
r
4
e
5
a
6
c
7
h
8
(
a
r
r
a
y
a
s
v
a
l
u
e
)
{
c
o
d
e
t
o
b
e
e
x
e
c
u
t
e
d
;
}
f
o
r
e
a
c
h
(
a
r
r
a
y
a
s
k
e
y
=
>
v
a
l
u
e
)
{
c
o
d
e
t
o
b
e
e
x
e
c
u
t
e
d
;
}
Example-
1
<
2
?
3
p
4
h
5
p
6
$
7
e
m
a
i
l
=
a
r
r
a
y
(
'
i
n
f
o
@
p
h
p
g
u
r
u
k
u
l
.
c
o
m
'
,
'
a
n
u
j
.
l
p
u
1
@
g
m
a
i
l
.
c
o
m
'
)
;
f
o
r
e
a
c
h
(
$
e
m
a
i
l
a
s
$
v
a
l
u
e
)
{
e
c
h
o
"
P
r
o
c
e
s
s
i
n
g
"
.
$
v
a
l
u
e
.
"
<
b
r
/
>
"
;
}
?
>
Output-
Processing [email protected]
Processing [email protected]
The Break Statement
Break end the execution of the for , for each , do-while or switch statement.
Syntax-
1
b
r
e
a
k
(
o
p
t
i
o
n
a
l
n
u
m
e
r
i
c
a
r
g
u
m
e
n
t
)
Example-
1
<
2
?
3
p
4
h
5
p
6
$
7
c
8
=
9
0
1
;
0
w
1
h
1
i
1
l
2
e
1
(
3
+
1
+
4
$
1
c
5
)
1
{
6
s
1
w
7
i
t
c
h
(
$
c
)
{
c
a
s
e
:
e
c
h
o
"
A
t
5
;
<
b
r
/
>
"
;
b
r
e
a
k
1
;
c
a
s
e
1
0
;
e
c
h
o
"
A
t
1
0
;
q
u
i
t
t
i
n
g
<
b
r
/
>
"
;
b
r
e
a
k
2
;
d
e
f
a
u
l
t
:
b
r
e
a
k
;
}
}
?
>
Output-
At 5;
At 10;quitting
The Continue Statement
“Continue” is used to skip the current loop iteration and continue with the next
iteration of the loop. But “Break” is used to exist from the whole loop.
Syntax –
1
c
o
n
t
i
n
u
e
(
o
p
t
i
o
n
a
l
n
u
m
e
r
i
c
a
r
g
u
m
e
n
t
)
;
Example –
1
<
2
?
3
p
4
h
5
p
6
f
7
o
8
r
9
(
1
$
0
c
=
0
;
$
c
<
=
1
0
;
+
+
$
c
)
{
i
f
(
$
c
=
=
5
)
{
c
o
n
t
i
n
u
e
;
}
p
r
i
n
t
"
$
c
n
"
;
}
?
>
Output – 0 1 2 3 4 6 7 8 9 10
PHP Arrays
Last Updated : 11 Mar, 2024
Arrays in PHP are a type of data structure that allows us to store multiple
elements of similar or different data types under a single variable thereby saving
us the effort of creating a different variable for every data. The arrays are helpful
to create a list of elements of similar types, which can be accessed using their
index or key.
Table of Content
Types of Array in PHP
Indexed or Numeric Arrays
Associative Arrays
Multidimensional Arrays
Suppose we want to store five names and print them accordingly. This can be
easily done by the use of five different string variables. But if instead of five, the
number rises to a hundred, then it would be really difficult for the user or
developer to create so many different variables. Here array comes into play and
helps us to store every element within a single variable and also allows easy
access using an index or a key. An array is created using an array() function in
PHP.
Types of Array in PHP
Indexed or Numeric Arrays: An array with a numeric index where
values are stored linearly.
Associative Arrays: An array with a string index where instead of linear
storage, each value can be assigned a specific key.
Multidimensional Arrays: An array that contains a single or multiple
arrays within it and can be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of element, but an index is
always a number. By default, the index starts at zero. These arrays can be
created in two different ways.
Examples of Indexed or Numeric Arrays
Example 1:
PHP
<?php
?>
Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV
<?php
?>
Output:
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav
The number of elements is 5
Looping using for:
ZACK
ANTHONY
RAM
SALIM
RAGHAV
Traversing: We can loop through the indexed array in two ways. First by using
for loop and secondly by using foreach. You can refer to PHP Loops for the syntax
and basic use.
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear
storage, every value can be assigned with a user-defined key of string type.
Examples of Associative Arrays
Example 1:
PHP
<?php
?>
Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina
<?php
Output:
Looping using foreach:
Husband is Zack and Wife is Zara
Husband is Anthony and Wife is Any
Husband is Ram and Wife is Rani
Husband is Salim and Wife is Sara
Husband is Raghav and Wife is Ravina
Looping using for:
zack zara
anthony any
ram rani
salim sara
raghav ravina
<?php
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];
?>
Output:
Dave Punk email-id is: [email protected]
John Flinch mobile number is: 9875147536
Example 2: We can traverse through the multidimensional array using for and
foreach loop in a nested way.
PHP
<?php
// Defining a multidimensional array
$favorites = array(
"Dave Punk" => array(
"mob" => "5689741523",
"email" => "[email protected]",
),
"Dave Punk" => array(
"mob" => "2584369721",
"email" => "[email protected]",
),
"John Flinch" => array(
"mob" => "9875147536",
"email" => "[email protected]",
)
);
?>
Output:
Dave Punk
mob : 2584369721
email : [email protected]
John Flinch
mob : 9875147536
email : [email protected]
PHP Array Functions
Function Description
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 and
"values" array
array_diff() Compare arrays, and returns the differences (compare values only
array_diff_assoc() Compare arrays, and returns the differences (compare keys and va
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and va
using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, u
user-defined key comparison function)
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and value
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and valu
a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, usi
defined key comparison function)
array_replace() Replaces the values of the first array with the values from followin
array_replace_recursive Replaces the values of the first array with the values from followin
() recursively
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 of
removed element
array_udiff() Compare arrays, and returns the differences (compare values only
user-defined key comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and va
using a built-in function to compare the keys and a user-defined fu
compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and va
using two user-defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, u
user-defined key comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and valu
a built-in function to compare the keys and a user-defined function
compare the values)
array_uintersect_uassoc Compare arrays, and returns the matches (compare keys and valu
() two user-defined key comparison functions)
each() Deprecated from PHP 7.2. Returns the current key and value pair f
array
extract() Imports variables into the current symbol table from an array
or
require 'filename';
PHP include Examples
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
ExampleGet your own PHP Server
<html>
<body>
</body>
</html>
Run example »
ADVERTISEMENT
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done
(we are using a <div> element so that the menu easily can be styled with CSS
later):
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
Run example »
Example 3
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling
file:
Example
<html>
<body>
</body>
</html>
Run example »
PHP include vs. require
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will
continue to execute:
Example
<html>
<body>
</body>
</html>
Run example »
If we do the same example using the require statement, the echo statement will
not be executed because the script execution dies after the require statement
returned a fatal error:
Example
<html>
<body>
</body>
</html>
Run example »
Use require when the file is required by the application.
Use include when the file is not required and application should continue when
file is not found.
PHP Type Casting
PHP allows us to convert the data type of any variable explicitly using certain
built-in keywords. Also, PHP can convert the data types by using the implicit
method.
Implicit Type Casting in PHP
PHP will automatically convert the type of a variable based on the value assigned
to them. This typecasting is called Implicit, which PHP does for us. For example, if
we declare a variable with an empty string and assign an integer value to it later
in the program, PHP will convert that variable datatype from a string into an
integer automatically.
Explicit Type Casting in PHP
Explicit type casting was done by programmers like us using the keywords
allowed by PHP language. Please find below the allowed type casting methods in
PHP,
(int) or (integer) – cast to an Integer
(bool) or (boolean) – cast to a Boolean
(float) or (double) or (real) – cast to a Float
(string) – cast to a String
(array) – cast to an Array
(object) – cast to an Object
We will learn about Implicit and Explicit type casting methods in detail below.
Also, gettype function used to get the current data type of a variable.
PHP Integer Type Casting
The Integer type casting method allows us to convert any values into integer
values. If the value contains floating-point numbers, fractions will be omitted,
and strings(without leading numbers) are converted into 0. Please find below the
examples,
Run this code
<?php
$a = (int) '42';
var_dump($a);
$b = (int) 10.5;
var_dump($b);
$c = (int) "5 best programming language";
var_dump($c);
$d = (int) "Best programming language";
var_dump($d);
?>
PHP Boolean Type Casting
The Boolean type casting method allows us to convert any values into the
boolean format. Please find below the examples,
Run this code
<?php
$a = (bool) '';
var_dump($a);
$b = (bool) 10.5;
var_dump($b);
?>
PHP Float Type Casting
The Float type casting method allows us to convert any values to floating-point
number. For some type, this will convert the value into integer first then it will
convert into float. please find below the examples,
Run this code
<?php
$number = '10.5';
var_dump($number);
$number = (float) '10.5';
var_dump($number);
$c = (string) 42;
var_dump($c);
$d = array(1,2,3,4,5);
var_dump($d);
$e = (string) $d;
var_dump($e);
$f = (bool) null
var_dump($f);
?>
PHP Array Type Casting
The Array type casting method is used to convert a single value from integer,
float, string, boolean data types into an array. The first element’s index always
will be 0, and the total count of an array is 1. Please find below the examples,
Run this code
<?php
$a = (array) 42;
echo gettype($a);
var_dump($a);
$b = (array) "Apple"
eco gettype($b);
var_dump($b);
?>
PHP Object Type Casting
The Object type casting method used to convert any values into an object, by
default it creates a new instance of the stdClass class. Please find below the
example,
Run this code
<?php
$numbers = array(1,2,3,4,5);
var_dump($numbers);