0

I have a very simple array where I want to be able to add settings as simple as possible. In my case, if I don't need a second value, I don't need to add it.

Code

$settings = [
  'my_string',
  'my_array' => 'hello'
];

print_r($settings);

Result

The problem with my approach is that my_string is seen as a value and the key 0 is added.

Array
(
    [0] => my_string
    [my_array] => hello
)

I could check if the key is a number and in that case figure out that I don't use a second value.

Is there a better approach?

I'm aware of that I can use multiple nested arrays but then simplicity is gone.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • Possible duplicate of [How can I force PHP to use strings for array keys?](https://stackoverflow.com/questions/3445953/how-can-i-force-php-to-use-strings-for-array-keys) – Sanu0786 Oct 15 '18 at 06:53
  • 1
    Try to use first value as array key and second (optional) as value, if not needed make value null/false. I think it might be a little simplier and clearer approach. – Jacek Rosłan Oct 15 '18 at 06:54
  • An array always is a key-value association. You can't not have a key or value. If you omit the key, you'll get an implicit numerical key. Now it depends on where you want the simplicity: in your parsing code, or when writing the array? Presumably you want a simple way to *write* the array, so, yes, in your parsing code you'll need to check whether the key is numeric then. – deceze Oct 15 '18 at 07:27

1 Answers1

1

The way you've written it, you wouldn't be able to access the value 'my_string' without some kind of key. There is always a key for any value, and if you don't specify values, PHP generates them as though they were indices in an actual array (PHP 'arrays' are actually dictionaries/maps/etc. that have default behavior in the absence of a specified key).

$settings = [
  'name' => 'my_string',
  'my_array' => 'hello'
];

If you don't want to use $settings[0] -- and I wouldn't want to either -- you should probably decide on a name for whatever 'my_string' is supposed to be and use that as its key.

kungphu
  • 4,592
  • 3
  • 28
  • 37