Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Variable exists and === true

I want to check if:

  • a field in the array isset
  • the field === true

Is it possible to check this with one if statement?

Checking if === would do the trick but a PHP notice is thrown. Do I really have to check if the field is set and then if it is true?

like image 981
Sebastian Sebald Avatar asked Oct 26 '11 19:10

Sebastian Sebald


Video Answer


3 Answers

If you want it in a single statement:

if (isset($var) && ($var === true)) { ... }

If you want it in a single condition:

Well, you could ignore the notice (aka remove it from display using the error_reporting() function).

Or you could suppress it with the evil @ character:

if (@$var === true) { ... }

This solution is NOT RECOMMENDED

like image 140
Madara's Ghost Avatar answered Sep 30 '22 05:09

Madara's Ghost


I think this should do the trick ...

if( !empty( $arr['field'] ) && $arr['field'] === true ){ 
    do_something(); 
}
like image 32
askome Avatar answered Sep 30 '22 06:09

askome


Alternative, just for fun

echo isItSetAndTrue('foo', array('foo' => true))."<br />\n";
echo isItSetAndTrue('foo', array('foo' => 'hello'))."<br />\n";
echo isItSetAndTrue('foo', array('bar' => true))."<br />\n";

function isItSetAndTrue($field = '', $a = array()) {
    return isset($a[$field]) ? $a[$field] === true ? 'it is set and has a true value':'it is set but not true':'does not exist';
}

results:

it is set and has a true value
it is set but not true
does not exist

Alternative Syntax as well:

$field = 'foo';
$array = array(
    'foo' => true,
    'bar' => true,
    'hello' => 'world',
);

if(isItSetAndTrue($field, $array)) {
    echo "Array index: ".$field." is set and has a true value <br />\n";
} 

function isItSetAndTrue($field = '', $a = array()) {
    return isset($a[$field]) ? $a[$field] === true ? true:false:false;
}

Results:

Array index: foo is set and has a true value
like image 33
Phill Pafford Avatar answered Sep 30 '22 07:09

Phill Pafford