16 – PHP Type Casting

0
722

In this tutorial, we’re going to discuss 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.

Next we’re going to modify our code using the gettype function that will tell us what type that we are working with.

Output:
14
string
integer

At this time, we’re going to switch the type for the ourselves. And we can do it using thesettype function is used to set the type of a variable. Here’s the modified code below using settype function.

 

Output:
14
string
integer
string

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.

 

Output:
14
string
integer
string
integer

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.