解析字符串转换成PHP中的布尔值 [英] Parsing a string into a boolean value in PHP

查看:1064
本文介绍了解析字符串转换成PHP中的布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我与PHP玩,我发现字符串值真与假,不能正确解析的条件布尔值,例如考虑以下功能:

Today I was playing with PHP, and I discovered that the string values "true" and "false" are not correctly parsed to boolean in a condition, for example considering the following function:

function isBoolean($value) {
   if ($value) {
      return true;
   } else {
      return false;
   }
}

如果我执行:

isBoolean("true") // Returns true
isBoolean("") // Returns false
isBoolean("false") // Returns true, instead of false
isBoolean("asd") // Returns true, instead of false

有似乎只以1的工作和0的值:

It only seems to work with "1" and "0" values:

isBoolean("1") // Returns true
isBoolean("0") // Returns false

有没有在PHP中的本地函数来解析真与假的字符串为布尔?

Is there a native function in PHP to parse "true" and "false" strings into boolean?

推荐答案

有是这样做的,它使用PHP的filter_var方法是原始的PHP方法:

There is a native PHP method of doing this which uses PHP's filter_var method:

$bool = filter_var($value, FILTER_VALIDATE_BOOLEAN);

据PHP手册:

的和是返回TRUE为1,真。否则,返回false。

Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

如果FILTER_NULL_ON_FAILURE被设置,就返回FALSE只为0,假,关,无,和,并返回NULL所有非布尔值。

If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

这篇关于解析字符串转换成PHP中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆