php isset() on a string variable using a string as index
Asked Answered
P

2

5

I have some strange issue with isset() function in PHP. Let me show... .

<?php

$aTestArray = array(
    'index' => array(
        'index' => 'Główna'
    ),
    'dodaj' => 'Dodaj ogłoszenie',
);

var_dump( isset($aTestArray['index']) );
var_dump( isset($aTestArray['index']['index']) );
var_dump( isset($aTestArray['dodaj']) );

var_dump( isset($aTestArray['index']['none']) );
var_dump( isset($aTestArray['index']['none']['none2']) );

// This unexpectedly returns TRUE
var_dump( isset($aTestArray['dodaj']['none']) );
var_dump( isset($aTestArray['dodaj']['none']['none2']) );


?>

The var_dump's will return:

bool(true)
bool(true)
bool(true)

bool(false)
bool(false)
bool(true)
bool(false)

Why the sixth var_dump() return TRUE ?

Pejsach answered 3/12, 2011 at 23:12 Comment(0)
T
12

When using the [] operators on a string, it will expect an integer value. If it does not get one, it will convert it. ['none'] is converted to [0] which, in your case, is a D.

Tiffanietiffanle answered 3/12, 2011 at 23:15 Comment(8)
Incorrect. One of the best features of PHP is that it does allow string keys; ['none'] is a valid key name.Blankenship
+1 Also good to explain that using [] on a string attempts to access its characters as array components.Lederman
@JamWaffles Absolutely! But that's when working with associative arrays. In this case we're doing something like 'Dodaj ogłoszenie'['none'], which does not support named keys.Tiffanietiffanle
@TomvanderWoerdt Ah I see now. I should have read the question more carefully - sorry!Blankenship
@JamWaffles echo $aTestArray['dodaj']['none']; --> DLederman
This by the way may change in PHP 5.4. This "feature" has been found problematic when seen together with string offset reading related changes in 5.4. It is currently being discussed to throw a notice in this case.Miscalculate
But why isn't ['dodaj']['none']['none2'] set then, too?Landlubber
['dodaj']['none'] is considered a "string offset" while ['dodaj'] is considered an actual string. While var_dump may list both as strings, they are not. In fact, you could get the error PHP Fatal error: Cannot use string offset as an array.Tiffanietiffanle
B
1

It is because PHP is written in C. So since $aTestArray['dodaj'] is the string:

$aTestArray['dodaj']['none']

is the same as

$aTestArray['dodaj'][0]

because

var_dump( (int) 'none')

is 0

Buddhism answered 3/12, 2011 at 23:25 Comment(1)
This answer would be much more useful if it were changed into an explanatory comment to Tom's answer.Sideboard

© 2022 - 2024 — McMap. All rights reserved.