panthro
panthro

Reputation: 24061

Check if a value isset and true or 'true'

I'm trying to output a required string if $required var is set and equal to bool true or string true.

I have:

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

So with the following set:

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

All good until:

$required = 'false' //required string set

How can I test the condition and allow for both string and bool types?

Upvotes: 1

Views: 226

Answers (2)

Stuart
Stuart

Reputation: 6795

How about using filter_var...:

filter_var($required, FILTER_VALIDATE_BOOLEAN);

Would give you:

$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

Saving the need to compare a bool and a string, so:

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

Further information for the random downvoter (hi r f):

Using FILTER_VALIDATE_BOOLEAN with filter_var will return the following, based on the input:

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

Upvotes: 3

Yoleth
Yoleth

Reputation: 1272

Try this :

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

Upvotes: 2

Related Questions