将布尔值转换为整数值php

use*_*361 39 php integer boolean type-conversion

是否有PHP的内置函数将采用布尔值并返回其整数等价?0表示FALSE,1表示TRUE?当然你可以轻松创建一个函数来做到这一点,我只是问一下PHP内部是否有内置函数.我已经尝试过intval()将它投射到(int)但是它们没有工作,它们在TRUE和FALSE两种情况下都返回0.

编辑:问题是它不是真正的布尔值,它是一个字符串"false","true",php没有检测到它传递了一个布尔值的jquery帖子.问题解决了,谢谢!

Jér*_*eil 67

http://www.php.net/manual/en/language.types.integer.php

通常,只是$myInt = (int)$myBoolean应该工作,你能告诉我们你的代码吗?


Daw*_*awa 16

只需在变量之前添加"+",如下所示:

$myBool = true; 

var_dump(+$myBool);

ouputs: int(1);
Run Code Online (Sandbox Code Playgroud)


Sam*_*ook 9

// cast to Integer
echo (int)true;         // 1
echo (int)false;        // 0

// get the integer value from argument
echo intval(true);      // 1
echo intval(false);     // 0

// simply echoing true returns 1
echo true;              // 1

// you can even add those values
echo true + true;       // 2
Run Code Online (Sandbox Code Playgroud)

  • 虽然这确实说明了这一点……添加一两句话来解释也无妨。 (24认同)
  • 但 `echo false;` 不返回 `0` (2认同)

小智 7

如果您不确定数据类型,请参见下面的示例,它适用于字符串、整数和布尔值。

<?php

$options = [ TRUE, FALSE, 'true', 'false', 1, 0, '1', '0', 'on', 'off', 'yes', 'no' ];

foreach ( $options as $option ) {
    $bool = filter_var( $option, FILTER_VALIDATE_BOOLEAN ); // TRUE or FALSE
    print (int) $bool . ' '; // 1 or 0
} 
// Outputs: 1 0 1 0 1 0 1 0 1 0 1 0 

?>
Run Code Online (Sandbox Code Playgroud)

filter_var( $var, FILTER_VALIDATE_BOOLEAN ) 将返回 bool(true) 或 bool(false) 然后简单地转换为整数。

filter_var()

(PHP 5 >= 5.2.0,PHP 7)

filter_var — 用指定的过滤器过滤变量


Sam*_*yne 5

如果您通过 AJAX POST 从 JSON IE 获取您的值,则该值将以字符串形式出现(如您所见)。解决此问题的一种方法是比较真/假字符串,然后将 bool 转换为 int

$requestBool = $_REQUEST['bool_value']; //This is 'true' or 'false'

$myInt = (int)($requestBool === 'true');
echo $myInt;

//returns: 0 or 1
Run Code Online (Sandbox Code Playgroud)