I'm having a problem with PHP's isset function. It's often and mysteriously (to me) misfiring.
For instance, when I have a variable that can be either a string or an error array, I try using isset to see if the variable contains one of the known indexes of the array, like so:
$a = "72";
if(isset($a["ErrorTable"]))
echo "YES";
else
echo "NO";
This bad boy prints YES all the way on my server. I tried it on Ideone (online interpreter thingie. It's cool!) here: http://ideone.com/r6QKhK and it prints out NO.
I'm thinking this has something to do with the PHP version we're using. Can someone shed some light into this?
Consider the following piece of code:
$a = "72";
var_dump( isset($a["ErrorTable"]) );
You're checking if $a["ErrorTable"]
is set. PHP first typecasts any non-numeric offset to int
and this makes ErrorTable
equal to 0
.
Essentially, you're just doing:
if ( isset($a[0]) )
Strings in PHP can be accessed an array, and $a[0]
is definitely set and the condition will evaluate to TRUE
.
However, this weird behavior was fixed in PHP 5.4.0 and the changelog for isset()
says:
5.4.0 -- Checking non-numeric offsets of strings now returns FALSE.
Your server is probably using an older version of PHP and that would explain why it outputs YES
.
You can use array_key_exists()
instead:
$a = "72";
if ( is_array($a) && array_key_exists('ErrorTable', $a) ) {
echo 'YES';
} else {
echo 'NO';
}
The output will be NO
on all PHP versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With