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,071
  • 5
  • 34
  • 66

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
  • 369,052
  • 73
  • 620
  • 1,021
Devon
  • 32,773
  • 9
  • 61
  • 91
  • Yes it's not empty but empty string! I'll update the question title – genespos Mar 01 '18 at 21:35
  • @LightnessRacesinOrbit An empty string still is has a way to be referenced. You can't do `$array = [ => "value" ]` but `$array = [ "" => "value"]` is fine. – Devon Mar 01 '18 at 21:39
  • @Devon: Yeah I'd misread genespos comment (mainly because the former example makes so little sense it hadn't even entered my mind!) – Lightness Races in Orbit Mar 01 '18 at 22:11
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,047
  • 1
  • 16
  • 31