Bifalgorithm post · Computer science one · Type Juggling
How can PHP values and variable states be converted and checked explicitly?
How can PHP values and variable states be converted and checked explicitly? (Computer science one · Type Juggling) — "Relying on type juggling to convert value…
Ideas in this flowchart
- PHP provides explicit value-conversion and variable-type checking functions.
- Relying on type juggling can be ugly and error prone; explicit conversion makes code more intentional.
- Conversion functions explicitly convert values while guaranteeing the indicated type.
- intval("10") converts the string to the integer 10.
- floatval("3.14") converts the string to the floating-point value 3.14.
- intval("ten") produces the integer value zero.
- Type-checking utilities determine whether a value is numeric or has a specific type.
- is_numeric($x) returns true for numbers and pure numeric strings, but false for nonnumeric strings such as "hello" and "10foo".
- is_int($x) returns true only for integers, while is_float($x) returns true only for floating-point numbers.
- gettype($x) provides a general type check.
- gettype($x) returns a string such as "boolean", "integer", "double", "string", "array", "object", "resource", "NULL", or "unknown type".
- Additional checker functions determine whether a variable is set, null, or empty.
- is_null($x) returns true when $x is unset or has been set to null.
- isset($x) returns true only when $x is set and not null.
- empty($x) returns true for an empty string, false, an empty array, null, "0", 0, or an unset variable.
- The comparison table shows that whitespace and the NULL byte are not empty, while zero values, false, an empty string, an empty array, null, and an unset variable are empty.
- For null or an unset variable, isset($var) is false, empty($var) is true, and is_null($var) is true.