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 ?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Incorrect. One of the best features of PHP is that it does allow string keys; ['none'] is a valid key name.
+1 Also good to explain that using [] on a string attempts to access its characters as array components.
@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.
@TomvanderWoerdt Ah I see now. I should have read the question more carefully - sorry!
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.
|
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

1 Comment

This answer would be much more useful if it were changed into an explanatory comment to Tom's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.