In this tutorial, we’re going to discuss about PHP Type Casting. We can call Type casting or Type Switching or Type Juggling. The idea here is that, out of all types we’ve been working in PHP such numbers or strings, we can actually switch from one type to another.
To start this application lets create a new PHP file called “typecasting.php”. And add the following code.
The PHP code below is trying to combine the string value of 10 to 4. Then we echo the variable value and it returns 14 meaning it will able to perform a mathematical operation. But this is a bad programming because we don’t want to make this switch for us, and we want a correct type to do the computation for us.
<HMTL>
<title>Type Casting</title>
<body>
<?php
$value1 = "10";//take note that this is a string
$value1 += 4; // and this a number
echo $value1;
?>
</body>
</HTML>
Next we’re going to modify our code using the gettype function that will tell us what type that we are working with.
<HMTL>
<title>Type Casting</title>
<body>
<?php
$value1 = "10 is my age";//take note that this is a string
$value2 = $value1 + 4; // and this a number
echo $value2;
echo '<br/>';
echo gettype($value1);//this will return a result as string echo '<br/>';
echo gettype($value2);//this will return a result as Integer
?>
</body>
</HTML>
Output:
At this time, we’re going to switch the type for the ourselves. And we can do it using the settype function is used to set the type of a variable. Here’s the modified code below using settype function.
<HMTL>
<title>Type Casting</title>
<body>
<?php
$value1 = "10 is my age";//take note that this is a string
$value2 = $value1 + 4; // and this a number
echo $value2;
echo '<br/>';
echo gettype($value1);//this will return a result as string echo '<br/>';
echo gettype($value2);//this will return a result as Integer echo '<br/>';
echo gettype($value2);//this will return a result as Integer
?>
</body>
</HTML>
Output:
The other way to set a type on something is going to be referring to it using the first type. And here’s the following code.
<HMTL>
<title>Type Casting</title>
<body>
<?php
$value1 = "10 is my age";//take note that this is a string
$value2 = $value1 + 4; // and this a number
echo $value2;
echo '<br/>';
echo gettype($value1);//this will return a result as string echo '<br/>';
echo gettype($value2);//this will return a result as Integer echo '<br/>';
echo gettype($value2);//this will return a result as Integer $value3 = (int) $value1;
echo '<br/>';
echo gettype($value3);//this will return a result as Integer
?>
</body>
</HTML>
Output:
14
string
integer
string
integer