Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it fine to keep an empty string as array key? [closed]

Tags:

arrays

php

key

I want to know is it fine if we keep an empty string as array key, like this

$test = array (
  '' => 'Select',
  1 => 'Internal',
  2 => 'External'
);

Any suggestions would be appreciated.

like image 269
yo black Avatar asked Jan 12 '16 07:01

yo black


1 Answers

Array keys should either be an integer or a string.
Dealing with empty string as array key is far from ideal practice.
Also Null will be cast to the empty string, i.e. the key null will actually be stored under "".
But such approach makes your array as ambiguous and erratic.
Consider the following examples:

$test = array (
  '' => 'Select',
  1 => 'Internal',
  2 => 'External',
  '' => 'select'
);

var_dump(array_key_exists('', $test));   // output 'bool(true)', not so bad - but only at first glance

the next case comes to ambiguity:

var_dump($test[""]);   // output "select"

and the last example comes to error(notice):

var_dump((object) $test);
// output: object(stdClass)#1 (3) { E_NOTICE : type 8 -- Illegal member variable name -- at line 12 [""]=> string(6) "select" [1]=> string(8) "Internal" [2]=> string(8) "External" }
like image 68
RomanPerekhrest Avatar answered Oct 10 '22 00:10

RomanPerekhrest