YouTip LogoYouTip

Php Boolval Function

# PHP boolval() Function The `boolval()` function in PHP is a built-in utility used to retrieve the boolean value of a variable. It performs a standard boolean cast on the input variable and returns either `true` or `false`. --- ## Introduction In PHP, variables of different data types (such as integers, strings, arrays, and objects) can be evaluated in a boolean context. The `boolval()` function provides a functional way to perform this conversion, offering an alternative to explicit type casting like `(bool) $var` or `(boolean) $var`. ### Version Requirements * **PHP 5** >= 5.5.0 * **PHP 7** * **PHP 8** --- ## Syntax ```php bool boolval(mixed $value) ``` ### Parameters * **`$value`**: The scalar or compound variable that you want to convert to a boolean. ### Return Value Returns the boolean value of `$value`. It will return `false` for values that are considered "empty" or "falsy" in PHP, and `true` otherwise. --- ## Code Examples ### Basic Usage The following example demonstrates how `boolval()` evaluates different data types, including integers, floats, strings, arrays, and objects. ```php ``` ### Output ```text 0: false 42: true 0.0: false 4.2: true "": false "string": true "0": false "1": true [1, 2]: true []: false stdClass: true ``` --- ## Considerations & Rules of Truthiness When using `boolval()`, PHP applies its standard rules for boolean casting. The following values are always evaluated as **`false`**: * The boolean `false` itself. * The integer `0` (zero) and `-0`. * The float `0.0` and `-0.0`. * An empty string `""`, and the string `"0"`. * An array with zero elements (`[]`). * The special type `NULL` (including unset variables). * SimpleXML objects created from empty tags (though this is an edge case). **Every other value** is evaluated as **`true`** (including any object, even if it has no properties, and any non-empty array). ### `boolval()` vs Explicit Casting `(bool)` There is no functional difference between using `boolval($var)` and casting with `(bool) $var`. * **`(bool) $var`** is a language construct and is slightly faster because it does not incur the overhead of a function call. * **`boolval($var)`** is a function, which makes it highly useful as a callback. For example, you can easily pass it to `array_map` or `array_filter`: ```php hello => 42 ) */ ?> ```
← Php Get_Defined_Vars FunctionC Examples Smallest Array Elem β†’