Explicit Type Casting in PHP

Notes:

Type Casting in PHP

Explicit type casting:
If required, programmers can also convert one type of data value to another type; which is known as explicit type casting.

Syntax:
(data type keyword) data value;
where:
data value can be a literal, variable name, or constant name

Name of the data type keywords for converting data values:
(integer), (int) – converts a given data value to an integer
(double), (float), (real) - converts a given data value to a double
(boolean), (bool) - converts a given data value to a boolean
(string) - converts a given data value to a string
(array) - converts a given data value to an array
(object) - converts a given data value to an object
(unset) - converts a given data value to NULL

Example Code:
echo (int) 3.142 , "<br/>"; // 3
echo (double) "3.142" , "<br/>"; // 3.142
echo (bool) 10 , "<br/>"; // 1
echo (string) 3.142, "<br/>"; // "3.142"

Name of the functions for casting data values:
intval(data value):integer
- returns integer value of a given data value
doubleval(data value):double
- returns double value of a given data value
boolval(data value):boolean
- returns boolean value of a given data value
strval(data value):string
- returns string value of a given data value

Example Code:
echo intval(3.142),"<br/>"; // 3
echo doubleval("3.142"),"<br/>"; // 3.142
echo boolval(true),"<br/>"; // 1
echo strval(3.142),"<br/>"; // "3.142"

Converting type of a variable:
If required we can convert the type of a variable also.
gettype(data value):string;
- returns the type of a given data value

settype($variableName,"data type"):bool;
- sets the type of a variable to a given data type

Example Code:
$num=10;
echo settype($num,"string"), "<br/>"; // 1
echo gettype($num), "<br/>"; // string
echo is_string($num), "<br/>"; // 1

Complete Code:
echo (int) 3.142; // 3
echo "<br/>";
echo (integer) 3.142; // 3
echo "<br/>";

echo (double)"3.142"; // 3.142;
echo "<br/>";
echo (float)"3.142"; // 3.142;
echo "<br/>";
echo (real)"3.142"; // 3.142;
echo "<br/>";

echo (boolean)10; // 1
echo "<br/>";
echo (bool)10; // 1
echo "<br/>";

echo (string)3.142; // 3.142
echo "<br/><br/>";

echo intval(3.142); // 3
echo "<br/>";
echo doubleval("3.142"); // 3.142
echo "<br/>";
echo boolval(10); // 1
echo "<br/>";
echo strval("3.142"); // 3.142
echo "<br/>";

$num=10;
echo gettype($num); // integer
echo "<br/>";
settype($num,"string");
echo gettype($num); // string

Interview Questions:

1. PHP stands for ______________
a. Hypertext Preprocessor
b. Preprocessor Hypertext
c. Personal Home Processor
d. Personal Hypertext processor
Ans: a