Home arrow PHP arrow Page 7 - The PHP Scripting Language

Automatic Type Conversion - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article



Automatic type conversion occurs when two differently typed variables are combined in an expression or when a variable is passed as an argument to a library function that expects a different type. When a variable of one type is used as if it were another type, PHP automatically converts the variable to a value of the required type. The same rules are used for automatic type conversion as demonstrated previously in Table 2-1.

Some simple examples show what happens when strings are added to integers and floats, and when strings and integers are concatenated:

// $var is set as an integer = 115
$var = "100" + 15;
// $var is set as a float = 115.0
$var = "100" + 15.0;
// $var is set as a string = "39 Steps"
$var = 39 . " Steps";

Not all type conversions are so obvious and can be the cause of hard-to-find bugs:

// $var is set as an integer = 39
$var = 39 + " Steps";
// $var is an integer = 42
$var = "3 blind mice" + 39;
// $var is a float, but what does it mean? $var = "test" * 4 + 3.14159;

Automatic type conversion can change the type of a variable. Consider the following example:

$var = "1";  // $var is a string == "1"
$var += 2;   // $var is now an integer == 3 $var /= 2;   // $var is now a float == 1.5 $var *= 2;   // $var is still a float == 3

Care must be taken when interpreting non-Boolean values as Boolean. Many library functions in PHP return values of different types in different circumstances. For example, many functions return the Boolean value false if a valid result could not be determined. If the function is successful, they return the valid integer, string, or compound type. However, a valid return value of 0, 0.0,"0", an empty string, null, or an empty array is also equal to the Boolean value false and can be misinterpreted as failure.

The solution is to test the type of the variable using the functions described in the next section.


Examining Variable Type and Content

Because PHP is flexible with types, it provides the following functions that can check a variable’s type:

boolean is_int(mixed variable)
boolean is_float(mixed variable)
boolean is_bool(mixed variable)
boolean is_string(mixed variable)
boolean is_array(mixed variable)
boolean is_object(mixed variable)

All the functions return a Boolean value oftrueorfalsedepending on whether the type of variable matches the variable type that forms the name of the function. For example, is_float( ) evaluates totruein the following code:

$test = 13.0;
// prints "Variable is a float"
if (is_float($test))
print "Variable is a float";

Is-identical and is-not-identical operators

While the PHP equals operator == tests the values of two variables, it doesn’t test the variables types. Consider the comparisons of string and integer variables:

$stringVar = "10 reasons to test variable type";
$integerVar = 10;
// Prints "Variables have the same value"
if ($stringVar == $integerVar)
print "Variables have the same value";

Because of PHP’s automatic type conversion,$stringVar == $integerVarevaluates totrue. PHP provides the is-identical operator===that tests not only values, but types. In the fragment below, the expression$stringVar === $integerVarevaluates tofalse:

$stringVar = "10 reasons to test variable type";
$integerVar = 10;
// Does not print anything
if ($stringVar === $integerVar)
print "Variables have the same value and type";

PHP also provides the is-not-identical operator,!==, that returnstrueif the value or type of two expressions are different.

Debugging with gettype(), print_r(), and var_dump( )

PHP provides the gettype( ),  print_r( ), and var_dump( )functions, which print the type and value of an expression in a human-readable form:

string gettype(mixed expression)
print_r(mixed expression)
var_dump(mixed expression [, mixed expression ...])

These functions are useful for debugging a script, especially when dealing with arrays or objects. To test the value and type of$variableat some point in the script, the following code can be used:

$variable = "3 Blind mice" + 39;

This prints:


While the var_dump( ) function allows multiple variables to be tested in one call, and provides information about the size of the variable contents, print_r( ) provides a more concise representation of arrays and objects, and will prove useful later when we start to use those variables.

The gettype( ) function simply returns the type name for an expression:

$variable = "3 Blind mice" + 39;
// prints: "integer"

The name that gettype( ) returns should only be used for information and not to programmatically test the type of a variable as the output is not guaranteed to remain stable with future PHP releases. To programmatically test a variable type, you should use the is_int( ), is_float( ), is_bool( ), is_string( ), is_array( ), or is_object( ) functions described earlier.

The gettype( ),  print_r( ), and var_dump( ) functions can be used on variables and expressions of any type, and we use them throughout the book to help illustrate the results of our examples.

Testing, setting, and unsetting variables

During the running of a PHP script, a variable may be in an unset state or may not yet be defined. PHP provides the isset( ) function and the empty( ) language construct to test the state of variables:

boolean isset(mixed var)
boolean empty(mixed var)

isset( ) tests if a variable has been set with a non-null value, while empty( ) tests if a variable is equal to false. The two are illustrated by the following code:

$var = 0;
// prints: "Variable is Set"
if (isset($var)) print "Variable is Set";
// prints: "Variable is Empty"
if (empty($var)) print "Variable is Empty";
$var = "test";
// prints: "Variable is Set"
if (isset($var)) print "Variable is Set";
// Doesn't print
if (empty($var)) print "Variable is Empty";

A variable can be explicitly destroyed using unset( ):

unset(mixed var [, mixed var [, ...]])

After the call tounsetin the following example,$varis no longer defined:

 $var = "foo";
// Later in the script
// Does not print
if (isset($var)) print "Variable is Set";

Table 2-2 show the return values forisset($var)andempty($var)when the variable$varis tested. Some of the results may be unexpected: when$varis set to"0,"empty( ) returnstrue.

Table 2-2. Expression values


State of the variable $var



unset $var;



$var = null;



$var = 0;



$var = true;



$var = false;



$var = "0";



$var = "";



$var = "foo";



$var = array();



A variable is always set when it is assigned a      value—with the exception of a null assignment—and isset( ) returnstrue. The empty( ) function tests the Boolean value of the variable and returns true if the variable isfalse. The statement

$result = empty($var);

is equivalent to

$result = not (boolean) $var;

However, PHP issues a warning when a cast operator is used on an unset variable, whereas empty( ) doesn’t.

>>> More PHP Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: