php 检查值是否已设置且为true或“true”

h9vpoimq  于 2023-02-11  发布在  PHP
关注(0)|答案(2)|浏览(160)

如果$required var被设置为bool true或string true,我将尝试输出所需的字符串。
我有:

isset($required) && $required == true ? 'required' : ''

因此,使用以下集合:

$required = true   //required string set
$required = 'true' //required string set
$required = false  //required string not set

一切正常,直至:

$required = 'false' //required string set

如何测试条件并允许字符串和bool类型?

kyks70gy

kyks70gy1#

如何使用filter_var ...:

filter_var($required, FILTER_VALIDATE_BOOLEAN);

会给予你:

$required = 'false';
filter_var($required, FILTER_VALIDATE_BOOLEAN); // false

$required = false;
filter_var($required, FILTER_VALIDATE_BOOLEAN); // false

$required = 'true';
filter_var($required, FILTER_VALIDATE_BOOLEAN); // true

$required = true;
filter_var($required, FILTER_VALIDATE_BOOLEAN); // true

省去了比较布尔值和字符串的需要,因此:

$required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
isset($required) && $required == true ? 'required' : '';

有关随机下选器(hi r f)的更多信息:
根据输入,将FILTER_VALIDATE_BOOLEANfilter_var一起使用将返回以下内容:

TRUE for "1", "true", "on" and "yes"
FALSE for "0", "false", "off" and "no"
NULL for anything else
tv6aics1

tv6aics12#

试试这个:

(isset($required) && ($required === true || $required === 'true')) ? 'required' : '';

相关问题