Login |  Register 
This has got to be one of the most frequently updated PHP sites, keep up the good work...
Max
 

Types in PHP

A variable can must be of a certain type but in PHP types are not explicitly defined, instead the variable type is determined by the context in which the variable is used. This means therefore that variables become a type when they are assigned a value that has a type.

Automatic type conversion

PHP automatically converts from one type to another, which can cause unexpected results. For instance converting from false to a string can have unexpected results.
$value = false;
echo "The value is $value";
//returns: The value is
To solve these kinds of problems PHP needs to be instructed how to deal with the variable.
$value = false;
echo "The value is " . (int)$value;
//returns: The value is 0

As you can see to cast a variable you need to use place the type you want to cast to in front of the variable in brackets. This then applies that type to the variable being cast. Note that you should be careful about what you cast as it can have some unexpected results. For instance casting a fraction to a integer will round the fraction to the nearest integer.

String conversion with numbers

Did you know you can add a sentance and a number together to form another number? Well in PHP you can! Unfortunatley this can lead to unexpected results so you need to be careful how you handle this.

$value = 1 + "4.5";
// is float with the value 5.5
$value = 1 + "tom";
// is integer with the value 1
$value = 1 + "2 Green Bottles";
// is integer with the value 3
$value = 1 + "Green Bottles 2";
// is integer with the value 3

As you can see when adding a string to a number if the first part of the string is a number this is then added together. Any other numbers are ignored. If you add a string with a float in it to a integer the result is a float. Again the correct way to solve this problem is to detect and or cast the variable to the correct type.

Detecting the type of a variable

A variable type can be identified by using the below functions simply pass the variable to the required function and it will return true if it is of that type. This is the a technique for defensive programming.

$var = "hello";
//Returns true if a variable is a BOOLEAN
is_bool($var)
//Returns true if a variable is a STRING
is_string($var)
//Returns true if a variable is a NUMERIC STRING
is_numeric($var)
//Returns true if a variable is an INTEGER
is_int($var)
//Returns true if a variable is an ARRAY
is_array($var)
//Returns true if a variable is an OBJECT
is_object($var)
//Returns true if a variable is NULL
is_null($var)
//Returns true if a variable is a FLOAT
is_float($var)

This is important as once a particular variables type has been identified you can then be certain of the effect of any operations performed on it.


No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38