Search blog

Sunday, November 12, 2017

Type Juggling and Type Casting in PHP

Type juggling and type casting can be used to change a value's type. While programming, it's important to know the type of the value and use type casting or juggling to convert it to compatible types.

Type Juggling:

When PHP converts a value from one type of value to another, it is called type juggling. PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

 $foo = "0"; // $foo is string (ASCII 48)  
 $foo += 2; // $foo is now an integer (2)  
 $foo = $foo + 1.3; // $foo is now a float (3.3)  

Type Casting:

When you explicitly set a type to change the value into another type, it is called type casting. PHP is a loosely typed language and assigns types to variables depending what is assigned to it. Variables coming from get/post and cookies etc are generally cast as strings rather than other types and there are often other times when you need to specifically cast a type in PHP as e.g. an integer.

An example of this in action is as follows, where $foo starts off as a string value and is then cast into an integer:

 $foo = '1';  
 echo gettype($foo); // outputs 'string'  
 settype($foo, 'integer');  
 echo gettype($foo); // outputs 'integer'   


Thank you for your Feedback!

Top 5 Posts (Weekly)