如果设置了$ 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类型?
答案 0 :(得分:3)
如何使用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
无需比较bool和字符串,所以:
$required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
isset($required) && $required == true ? 'required' : '';
随机downvoter的更多信息(hi r f):
将FILTER_VALIDATE_BOOLEAN
与filter_var
一起使用将根据输入返回以下内容:
TRUE for "1", "true", "on" and "yes"
FALSE for "0", "false", "off" and "no"
NULL for anything else
答案 1 :(得分:2)
试试这个:
(isset($required) && ($required === true || $required === 'true')) ? 'required' : '';