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

Unit 2 (php)

The document covers PHP conditional statements and looping constructs, detailing their syntax and usage with examples. It explains various types of conditional statements such as if, if-else, if-elseif-else, and switch, as well as looping statements like while, do-while, for, and foreach. Additionally, it introduces PHP arrays, including indexed, associative, and multidimensional arrays, along with their creation and traversal methods.

Uploaded by

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

Unit 2 (php)

The document covers PHP conditional statements and looping constructs, detailing their syntax and usage with examples. It explains various types of conditional statements such as if, if-else, if-elseif-else, and switch, as well as looping statements like while, do-while, for, and foreach. Additionally, it introduces PHP arrays, including indexed, associative, and multidimensional arrays, along with their creation and traversal methods.

Uploaded by

divyashree
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 2

PHP Conditional Statements


Conditional Statements are used to perform actions based on different
conditions. Sometimes when we write a program, we want to perform some
different actions for different actions. We can solve this by using conditional
statements.
In PHP we have these conditional statements:
1. if Statement.
2. if-else Statement
3. If-elseif-else Statement
4. Switch statement

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";
}
?>

What is Looping Statement In PHP?


Loops execute a block of code a specified number of times, or while a specified
condition is true.
Type of Loops in PHP
 The while Loop
 The Do …while Loop
 The For Loop
 The Foreach Loop
 Break and Continue Statement
The While Loop
While structure is the another type of loop statement, where the condition is
checked at first, the iteration will not stop even if the value changes while
executing Statements.
Syntax-
1
w
2
h
3
i
4
l
e
(
c
o
n
d
i
t
i
o
n
)
{
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
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

// One way to create an indexed array


$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly


echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";

// Second way to create an indexed array


$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";

// Accessing the elements directly


echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";

?>

Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV

Example 2: We can traverse an indexed array using loops in PHP.


 PHP

<?php

// Creating an indexed array


$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// One way of Looping through an array using foreach


echo "Looping using foreach: \n";
foreach ($name_one as $val){
echo $val. "\n";
}
// count() function is used to count
// the number of elements in an array
$round = count($name_one);
echo "\nThe number of elements are $round \n";

// Another way to loop through the array using for


echo "Looping using for: \n";
for($n = 0; $n < $round; $n++){
echo $name_one[$n], "\n";
}

?>

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

// One way to create an associative array


$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");

// Second way to create an associative array


$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";

// Accessing the elements directly


echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";

?>

Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina

Example 2: We can traverse associative arrays in a similar way did in numeric


arrays using loops.
 PHP

<?php

// Creating an Associative Array


$name_one = [
"Zack" => "Zara",
"Anthony" => "Any",
"Ram" => "Rani",
"Salim" => "Sara",
"Raghav" => "Ravina",
];

// Looping through an array using foreach


echo "Looping using foreach: \n";
foreach ($name_one as $val => $val_value) {
echo "Husband is " . $val . " and Wife is " . $val_value . "\n";
}

// Looping through an array using for


echo "\nLooping using for: \n";
$keys = array_keys($name_one);
$round = count($name_one);

for ($i = 0; $i < $round; ++$i) {


echo $keys[$i] . " " . $name_one[$keys[$i]] . "\n";
}
?>

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

Traversing Associative Arrays: We can loop through the associative 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.
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index
instead of a single element. In other words, we can define multi-dimensional
arrays as an array of arrays. As the name suggests, every element in this array
can be an array and they can also hold other sub-arrays within. Arrays or sub-
arrays in multidimensional arrays can be accessed using multiple dimensions.
Examples of Multidimensional Arrays
Example 1:
 PHP

<?php

// Defining a multidimensional array


$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "[email protected]",
)
);

// 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]",
)
);

// Using for and foreach in nested form


$keys = array_keys($favorites);
for($i = 0; $i < count($favorites); $i++) {
echo $keys[$i] . "\n";
foreach($favorites[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}

?>

Output:
Dave Punk
mob : 2584369721
email : [email protected]
John Flinch
mob : 9875147536
email : [email protected]
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 and
"values" array

array_count_values() Counts all the values of an 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_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 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_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 retur


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 an 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 followin

array_replace_recursive Replaces the values of the first array with the values from followin
() 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 of
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 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)

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 array

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

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

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 pair f
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 ke

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

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 function


maintains the index association

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

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

PHP Include Files


❮ PreviousNext ❯
The include (or require) statement takes all the text/code/markup that exists in
the specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or
text on multiple pages of a website.
PHP include and require Statements
It is possible to insert the content of one PHP file into another PHP file (before the
server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
 require will produce a fatal error (E_COMPILE_ERROR) and stop the script
 include will only produce a warning (E_WARNING) and the script will
continue
So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file is
accidentally missing.
Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header needs
to be updated, you can only update the header include file.
Syntax
include 'filename';

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 &copy; 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>

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


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

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

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


<p>Some text.</p>
<p>Some more text.</p>

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

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


<?php include 'vars.php';
echo "I have a $color $car.";
?>

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

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


<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

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

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


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</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);

$number = (double) '10.5';


var_dump($number);

$number = (real) '10.5';


var_dump($number);
?>
PHP String Type Casting
The String type casting method allows us to convert any values into the string
format. A boolean values such as true, false converted into 1, “”(empty string)
respectively and null value always converted into “”(empty string). Please find
below the examples,
Run this code
<?php
$a = (bool) true;
var_dump($a);
$b = (string) $a;
var_dump($b);

$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);

$object = (object) $numbers


var_dump($object);
?>
We learned about different type casting methods available in PHP. These can be
used effectively when we write a program with strict data type conversion. Let’s
move to the next chapter of this tutorial series.

You might also like