What is Typecasting in php?

File name : index.php

<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
The casts allowed are:

(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)
(binary) casting and b prefix forward support was added in PHP 5.2.1

Note :-

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>
Casting literal strings and variables to binary strings:

<?php
$binary = (binary) $string;
$binary = b"binary string";
?>
Note:
Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.
<?php
$foo = 10; // $foo is an integer
$str = "$foo"; // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
echo "they are the same";
}
?>

Converting to an integer works only if the input begins with a number
(int) "5txt" // will output the integer 5
(int) "before5txt" // will output the integer 0
(int) "53txt" // will output the integer 53
(int) "53txt534text" // will output the integer 53


<?php
$foo = "1"; // $foo is string (ASCII 49)
$foo *= 2; // $foo is now an integer (2)
$foo = $foo * 1.3; // $foo is now a float (2.6)
$foo = 5 * "10 Little Piggies"; // $foo is integer (50)
$foo = 5 * "10 Small Pigs"; // $foo is integer (50)
?>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here