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?

7
  • Where do you get the array from? What are you using it for? If it's good or bad depends on the use case. Commented Mar 1, 2018 at 21:32
  • how could I reach my goal? What is your goal? :) Commented Mar 1, 2018 at 21:32
  • @Litty I mean an equivalent of the second array. Anyway I've got answers Commented Mar 1, 2018 at 21:34
  • 'Some items', implies you may have more than one empty string as a key, which of course will result in clobbering. Perhaps you should generate unique ids for these. Commented Mar 1, 2018 at 22:10
  • You also should the double arrow operator => for key value pairs when defining arrays. Commented Mar 1, 2018 at 22:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it's not empty but empty string! I'll update the question title
@LightnessRacesinOrbit An empty string still is has a way to be referenced. You can't do $array = [ => "value" ] but $array = [ "" => "value"] is fine.
@Devon: Yeah I'd misread genespos comment (mainly because the former example makes so little sense it hadn't even entered my mind!)
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.