Php array offset goes through "isset" even though it is not set

The easiest way 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 comes back as:

Apparently it is installed ...

Warning: Invalid line offset "two" in C: \ test.php on line 6

h

Is it because there are mixed key types? It was a small anomaly that I encountered and I was wondering if anyone could shed some light on it ...

+3


source to share


3 answers


The reason is that when a string is dereferenced, it returns a string containing one character (assuming the index does not exceed the length); the resulting string can be dereferenced again (from 5.4 onwards).

For example - link :

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

      

Invalid indexes, such as 'two'

, raise a notification, but are treated like an index 0

unless used internally isset()

.



Another example:

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

      

If you donโ€™t know in advance if a string or an array was passed and this is important to you, you need to do additional type checks between each path.

+4


source


You should check all your array keys before trying to use them, i.e. all the way up the chain. isset()

takes multiple parameters
, so you don't need to rewrite it and can keep the DRY principles a bit more:



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

      

0


source


isset

returns odd and unexpected results when you pass them a string instead of an array.

It is good practice to concatenate a check is_array

with a check isset

.

-1


source







All Articles