2

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?

genespos
  • 3,211
  • 6
  • 38
  • 70

2 Answers2

5

There's no such thing as an empty key. The key can be an empty string, but you can still access it always at $groups[""].

The useful thing of associative arrays is the association, so whether it makes sense to have an empty string as an array key is up to how you associate that key to the value.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
2

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];
Ivan Kalita
  • 2,197
  • 1
  • 18
  • 31