Automatic type conversion

As PHP is loosely typed, it will automatically convert one type to another whenever possible. Problems with automatic conversion occur when either no meaningful conversion is possible, or when conversion yields unexpected results. For example, calling "print" on an array makes PHP print out "Array"; it doesn't automatically convert the array to a string of all its elements. Treating an object like a string has its own unique behaviour, but that's not too important right now.

The unexpected results occur when PHP converts values and produces unhelpful results. This is not PHP being badly written, more that your code needs to be more explicit. For example, converting from a boolean to a string will produce a 1 if the boolean is set to true, or an empty string if false. Consider this script:

<?php
    $bool = true;
    print "Bool is set to $bool\n";
    $bool = false;
    print "Bool is set to $bool\n";
?>

That will output the following:

Bool is set to 1
Bool is set to

As you can see, it hasn't printed out a 0 for false. Instead, nothing is printed, which makes the output look incorrect. To solve this problem, and others like it, tell PHP how you want the value converted by typecasting. The above script should be rewritten to typecast the boolean to an integer, as this will force boolean true to be 1 and boolean false to be 0.

<?php
    $bool = true;
    print "Bool is set to $bool\n";
    $bool = false;
    print "Bool is set to ";
    print (int)$bool;
?>

This time the script outputs 1 and 0 as we wanted.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Forcing a type with type casting >>

Previous chapter: Checking a variable is set

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.