{| align=”center” class=”php-chapter-nav” cellpadding=”0” cellspacing=”50” !width=”33%”| [[PHP:_From_Beginner_to_Pro|← Table of Contents]] !!width=”33%”| ”’Advanced Topic: Manual Type Casting”’ !!width=”33%”| |}

Sometimes letting PHP decide the data type on its own can produce improper or unexpected results. Consider this example:

<?php // Imagine that you want to see if a variable is true or false. $isTrueOrFalse = NULL; // if ($isTrueOrFalse == FALSE) will return TRUE. $isTrueOrFalse = 0; // if ($isTrueOrFalse == FALSE) will return TRUE. $isTrueOrFalse = “0”; // if ($isTrueOrFalse == FALSE) will return TRUE.

// What if you wanted to see if it was true? $isTrueOrFalse = 1; // if ($isTrueOrFalse == TRUE) will return TRUE. $isTrueOrFalse = “1”; // if ($isTrueOrFalse == TRUE) will return TRUE. $isTrueOrFalse = “false”; // if ($isTrueOrFalse == TRUE) will return TRUE.

// All of these values could be unexpected and end up breaking your application.

To get around this, there are two approaches: * ”’Use [http://www.php.net/manual/en/function.settype.php the settype() function] to manually change the variable’s type”’: $isTrueOrFalse = “0”; var_dump($isTrueOrFalse); // Output: string(1) “0” settype($isTrueOrFalse, bool); var_dump($isTrueOrFalse); // Output: bool(false)

  • ”’Use [http://php.net/manual/en/language.types.type-juggling.php dynamic type casting] to only evaluate a variable as a specific type”’: $isTrueOrFalse = “0”; var_dump($isTrueOrFalse); // Output: string(1) “0” var_dump((bool)$isTrueOrFalse); // Output: bool(false) var_dump($isTrueOrFalse); // Output: string(1) “0”

In the majority of cases where either approach is necessary, dynamic type casting is considered the safest.

{| align=”center” class=”php-chapter-nav” cellpadding=”0” cellspacing=”50” !width=”33%”| [[PHP:_From_Beginner_to_Pro|← Table of Contents]] !!width=”33%”| ”’Advanced Topic: Manual Type Casting”’ !!width=”33%”| |} [[Category:PHP_From_Beginner_to_Pro]] [[Category:PHPBook:Advanced Topics]]