Have an account? Sign in
Login  Register  Facebook
This Page is Under Construction! - If You Want To Help Please Send your CV - Advanced Web Core (BETA)
Quick Table of Contents
[Edit] Converting Between Data Types Using Type Casting
Converting values from one datatype to another is known as type casting. A variable can be evaluated once as a different type by casting it to another. This is accomplished by placing the intended type in front of the variable to be cast. A type can be cast by inserting one of the operators shown in Table 3-2 in front of the variable.

Type Casting Operators

Cast OperatorsCast Operators
(array)Array
(bool) or (boolean)Boolean
(int) or (integer)Integer
(object)Object
(real) or (double) or (float)Float
(string)String
Let’s consider several examples. Suppose you’d like to cast an integer as a double:
$score = (double) 13; // $score = 13.0
Type casting a double to an integer will result in the integer value being rounded down, regardless of the decimal value. Here’s an example:
$score = (int) 14.8; // $score = 14
What happens if you cast a string datatype to that of an integer? Let’s find out:
$sentence = "This is a sentence";
echo (int) $sentence; // returns 0
While likely not the expected outcome, it’s doubtful you’ll want to cast a string like this anyway. You can also cast a datatype to be a member of an array. The value being cast simply becomes the first element of the array:
$score = 1114;
$scoreboard = (array) $score;
echo $scoreboard[0]; // Outputs 1114
Note that this shouldn’t be considered standard practice for adding items to an array because this only seems to work for the very first member of a newly created array. If it is cast against an existing array, that array will be wiped out, leaving only the newly cast value in the first position. One final example: any datatype can be cast as an object. The result is that the variable becomes an attribute of the object, the attribute having the name scalar:
$model = "Toyota";
$obj = (object) $model;
The value can then be referenced as follows:
print $obj->scalar; // returns "Toyota"
September 12, 2011