What are the main scalar and compound data types in PHP, and how does PHP handle type conversion between them?
Last updated
PHP has four scalar types (int, float, string, bool) and compound types (array, object, callable, iterable), plus the special types null and resource; it converts between them automatically (juggling) based on context.
Scalar types: Hold a single value:
int,float,string, andbool.Compound types: Hold multiple values or structures:
arrayandobject(withcallableanditerableas pseudo-types).Type juggling (implicit conversion): In an arithmetic context a numeric string becomes a number; in a boolean context
0,"","0",null, and empty arrays are falsy.Explicit casting: Force a type with casts like
(int),(string),(bool), or functions likeintval()andsettype().Comparison caveat: Use
===to avoid surprising loose-comparison juggling;==converts types before comparing.
- https://www.php.net/ChangeLog-5.php
- https://stackoverflow.com/questions/6623130/scalar-vs-primitive-data-type-are-they-the-same-thing
- https://www.scribd.com/document/887962107/PHP-Questions-and-Answers
- https://stackoverflow.com/questions/13012195/typecast-function-parameters
- https://stackoverflow.com/questions/4754318/why-is-traditional-type-hinting-not-allowed-in-php
- https://www.freecodecamp.org/news/how-php-type-juggling-works-explained-with-code-examples/