Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php isset() on a string variable using a string as index

Tags:

arrays

php

isset

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 ?

like image 862
BlueMan Avatar asked Dec 03 '11 23:12

BlueMan


People also ask

What's the difference between isset () and Array_key_exists ()?

Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.

What is isset ($_ GET in PHP?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

Does Isset check for empty string?

isset: Returns true for empty string, False, 0 or an undefined variable.


2 Answers

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.

like image 114
Tom van der Woerdt Avatar answered Oct 09 '22 18:10

Tom van der Woerdt


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

like image 38
Sergej Brazdeikis Avatar answered Oct 09 '22 19:10

Sergej Brazdeikis