user998066 user998066 - 10 months ago 39
PHP Question

PHP, easier way to get array values without warnings


is there a more concise way to write the statement below? If I don't check if an array key exists I get a PHP warning. However, the below is a bit too, ehm, wordy.


$display_flag = false;
if (array_key_exists('display_flag',$pref_array) {
$display_flag = $pref_array['display_flag'];


The way you have it is fine, as you should validate if the value actually exists, but you could also do a ternary op:

$display_flag = (isset($pref_array['display_flag'])) ? (bool) $pref_array['display_flag'] : false;

I typecast the contents of display_flag to bool if it is set, so you are ensured a boolean value in either case.

Also you could (but I don't recommend it), squelch the warning with the @:

$display_flag = @$pref_array['display_flag'];