⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

PHP Type Casting

Data conversion or Type Casting allows us to manually change a variable's data type. This is extremely useful when receiving data from external sources (such as user input via forms or APIs), which is always passed as a string, but we want to use it for calculations or logical validations. In PHP, casting is performed by writing the desired data type inside parentheses before the variable.

EXAMPLE
RESULT
The result will be displayed here...

Allowed Types for Casting

You can use the following keywords inside the parentheses:

⚠️ Hidden Pitfalls during Conversion

PHP is very flexible with type casting, which can sometimes lead to unexpected results:

  1. Converting a string to a number: If you cast the string "15 kilometers" into an integer (int), PHP will return 15. However, if the string starts with text, e.g., "Team 15", the result will be 0!
  2. Converting to a Boolean value: All values become true, except those considered "empty". The following will cast to false: the number 0, the string "0", an empty string "", and an empty array.