How to convert numeric value to boolean type in php

青灯夜游
Release: 2023-03-14 18:04:02
Original
2903 people have browsed it

Conversion: 1. Use the double logical NOT operator with the syntax "!!Number to be converted"; 2. Add the target type "(bool)" enclosed in parentheses before the numerical variable to be converted. Or "(boolean)", for example "(bool) value"; 3. Use the boolval() function, the syntax is "boolval (value)".

How to convert numeric value to boolean type in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts numerical values For Boolean type

1, use the double logical NOT operator "!!"

to perform a Boolean value Negation operation. For example: !true = false, !false = true, !10 = false.

<?php
var_dump(!!2);  //返回true
var_dump(!!0);  //返回false
var_dump(!!1);  //返回true
?>
Copy after login

How to convert numeric value to boolean type in php

2. Add the target type "(bool)" or "(boolean)" enclosed in parentheses before the conversion variable

  • (bool), (boolean): Convert to Boolean type

<?php
var_dump((bool)2);  //返回true
var_dump((bool)0);  //返回false
var_dump((bool)1);  //返回true
var_dump((bool)100);  //返回true
?>
Copy after login

How to convert numeric value to boolean type in php

3. Use boolval() function

boolval(): used to obtain the Boolean value of the variable;

<?php
echo &#39;0:        &#39;.(boolval(0) ? &#39;true&#39; : &#39;false&#39;)."<br>";
echo &#39;42:       &#39;.(boolval(42) ? &#39;true&#39; : &#39;false&#39;)."<br>";
echo &#39;0.0:      &#39;.(boolval(0.0) ? &#39;true&#39; : &#39;false&#39;)."<br>";
echo &#39;4.2:      &#39;.(boolval(4.2) ? &#39;true&#39; : &#39;false&#39;)."<br>";
echo &#39;"0":      &#39;.(boolval("0") ? &#39;true&#39; : &#39;false&#39;)."<br>";
echo &#39;"1":      &#39;.(boolval("1") ? &#39;true&#39; : &#39;false&#39;)."<br>";
?>
Copy after login

Output result:

0:        false
42:       true
0.0:      false
4.2:      true
"0":      false
"1":      true
Copy after login

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to convert numeric value to boolean type in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template