Search code examples
phpassociative-arrayarray-key

Using empty string as key in associative array


I need to select and group some items according to some values and it's easy using an associative multidimensional array:

$Groups = array(
    "Value1" = array("Item1", "Item3"),
    "Value2" = array("Item2", "Item4")
    );

But some items hasn't the value so my array will be something like:

$Groups = array(
    "Value1" = array("Item1", "Item3"),
    "Value2" = array("Item2", "Item4")
    "" = array("Item5", "Item6")
    );

I've tested it (also in a foreach loop) and all seems to work fine but I'm pretty new to php and I'm worried that using an empty key could give me unexpected issues.

Is there any problem in using associative array with empty key?
Is it a bad practice?
If so, how could I reach my goal?


Solution

  • You can use an empty string as a key, but be careful, cause null value will be converted to empty string:

    <?php
    
    $a = ['' => 1];
    
    echo $a[''];
    // prints 1
    
    echo $a[null];
    // also prints 1
    

    I think, it's better to declare some "no value" constant (which actually has a value) and use it as an array key:

    <?php
    
    define('NO_VALUE_KEY', 'the_key_without_value');
    
    $a = [NO_VALUE_KEY => 1];