Home » Php » php – Is it fine to keep an empty string as array key?

php – Is it fine to keep an empty string as array key?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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" }

Answer:

This will work fine but not good approach. For example, if you need to check null key of array then this empty string will return true. This approach will make syntax errors in other strictly typed languages like java and C.
So its better to avoid such coding 🙂