Is it okay to keep an empty string as an array key?

I want to know if this is fine if we save the empty string as an array key, e.g.

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

Any suggestions would be appreciated.

+5
source share
2 answers

Array keys must be integer or string. Working with an empty string as an array key is far from ideal practice.
Also, Null will be passed to an empty string, i.e. The null key will actually be stored under "".
But this approach makes your array ambiguous and unstable.
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 following case leads to ambiguity:

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

and the last example is an error (notification):

 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" } 
+2
source

This will work fine, but not very well. For example, if you need to check the null key of an array, this empty string will return true. This approach will make syntax errors in other strongly typed languages, such as java and C. Therefore, it is better to avoid such coding :)

+1
source

Source: https://habr.com/ru/post/1240408/


All Articles