Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php array offset passes 'isset', even though it's not set

Tags:

php

The easiest way for me to explain this is to show an example ... Here's a replication of the problem code:

<?php
    $test=array();
    $test['one']='hello';
    if(isset($test['one']['two'][0])) {
        echo 'Apparently it is set ...';
        echo $test['one']['two'][0];
   }
?>

This returns as:

Apparently it is set ...

Warning: Illegal string offset 'two' in C:\test.php on line 6

h

Is this because there are mixed key types? It's just a little anomaly I came across and was wondering if someone could shed some light on it ...

like image 925
Just Lucky Really Avatar asked Nov 27 '25 05:11

Just Lucky Really


1 Answers

The reason is that, when you dereference a string, it will return a string comprising a single character (assuming the index doesn't exceed the length); the resulting string can be dereferenced again (starting from 5.4 onwards).

For example - link:

$s = 'hello';
$s[0];    // "h"
$s[0][0]; // "h"
// etc. etc.

Illegal indices such as 'two' will cause a notice but it's treated as index 0, except when used inside isset().

Another example:

$s[0][1];    // ""
$s[0][1][0]; // notice: uninitialised string offset: 0

If you don't know beforehand whether a string or array is passed and this is important to you, additional type checks need to take place in between each path.

like image 200
Ja͢ck Avatar answered Nov 28 '25 19:11

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!