• PHP Video Tutorials

PHP - boolval() Function



Definition and Usage

The boolval() function is a PHP inbuilt function. It gets the boolean value of a variable.

Syntax

bool boolval( mixed $value )

Parameters

Sr.No Parameter & Description
1

value

The scalar value being converted to a boolean value. It can be a string type, integer type, object and etc.

*mixed: mixed indicates that a parameter may accept multiple (but not necessarily all) types

Return Values

This function returns a boolean value (TRUE or FALSE). Below is a list of different variable types and their return value (TRUE or FLASE) on conversion to boolean value −

  • integer − if value is 0 then boolval() returns false. For any other value returns true.
  • float − if value is 0.0 then boolval() returns false. For any other value returns true.
  • string − if string value is "0" and null then boolval() returns false. For any other value returns true (even "0.0").
  • array − if value is empty array then boolval() returns false. For any other value returns true.
  • object − if object is null then boolval() returns false. For any other value returns true.
  • null − boolval() always returns false when variable is null.

Dependencies

PHP 5.5 and above

Example

Following example demonstrates return values with different types of variables −

<?php
   // PHP program demo for boolval() function
   echo 'boolval of 4: '.( boolval( 4 )? 'true' : 'false');
   echo 'boolval of -4: '.( boolval( -4 )? 'true' : 'false');
   echo 'boolval of 0: ' .( boolval( 0 )? 'true' : 'false');
   echo 'boolval of 4.5: '.( boolval( 4.5 )? 'true' : 'false');
   echo 'boolval of -4.5: '.( boolval( -4.5 )? 'true' : 'false' );
   echo 'boolval of 0.0: '.( boolval( 0.0 )? 'true' : 'false' );
   echo 'boolval of "1": '.( boolval( "1" )? 'true' : 'false' );
   echo 'boolval of "0": '.( boolval( "0" )? 'true' : 'false' );
   echo 'boolval of "0.0": '.( boolval( "0.0" )? 'true' : 'false' );
   echo 'boolval of "abc": '.( boolval( "abc" )? 'true' : 'false' );
   echo 'boolval of "": '.( boolval( "" )? 'true' : 'false' );
   echo 'boolval of [2, 3]: '.( boolval( [1, 5] )? 'true' : 'false' );
   echo 'boolval of []: '.( boolval( [] )? 'true' : 'false' );
   echo 'boolval of NULL: '.( boolval( NULL )? 'true' : 'false' );
?>

Output

This will produce following result −

boolval of 4: true
boolval of -4: true
boolval of 0: false
boolval of 4.5: true
boolval of -4.5: true
boolval of 0.0: false
boolval of "1": true
boolval of "0": false
boolval of "0.0": true
boolval of "abc": true
boolval of "": false
boolval of [2, 3]: true
boolval of []: false
boolval of NULL: false
php_function_reference.htm
Advertisements