Reputation: 517
Could anyone please explain to me why the following line of code prints out true?
$a = "string";
if(isset($a['error'])) echo true; else echo false;
When I do a function call, I return the expected data if it worked properly, or return array("error" => $error)
;
Then on receiving the returned data I check if isset($var['error']) and if its not then I know I received some expected data.
I would also appreciate if you could advice me if this a good or bad way of handling data between function calls? And if there is a better "good practice" for this.
Upvotes: 1
Views: 116
Reputation: 47956
I'm not 100% sure why the behavior is like this, but I do know that PHP allows you to handle strings in a similar way as an array.
$a = "StackOverflow";
echo $a[2]; // a
echo $a[4]; // k
echo $a[6]; // v
echo $a[8]; // r
Now when you pass a string key as an index of the array, PHP will try to parse that string into a numerical value to use as a key.
echo $a['stack']; // S
echo $a['over']; // S
echo $a['flow']; // S
echo $a['0stack']; // S
echo $a['1over']; // t
echo $a['2flow']; // a
echo $a['3flow']; // c
echo $a['4flow']; // k
Upvotes: 0
Reputation: 157839
Well, this is some of PHP misbehaviors, which luckily has been fixed in some recent version.
You can address a single character in a string using the same square braces used to address an array element.
'error'
evaluates to 0 and then you have got $a[0]
which is set.
to fix that you have to check if $a is array first
Upvotes: 3
Reputation: 16923
I believe it's a bug and it's fixed in PHP 5.4+: http://codepad.viper-7.com/fz1rnT
looks like isset($str[$key])
in same way as isset($str[intval($key)])
, where $str
and $key
are strings
To handle errors best approach are exceptions:
Upvotes: 0