Home » Php » Is it a bad practice to use spaces in PHP associative array indexes?

Is it a bad practice to use spaces in PHP associative array indexes?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have to pass some parameters using an associative array, something like this:

$blockGroup['name=products type=complete']

Doing some tests i saw that it works, but is it a bad practice? Is it possible to generate any bug or unexpected behavior?

Thanks for any suggestion!

EDIT 1

I am using this array in a view implementation, the complete structure is:

$blockGroup['name=products type=complete'][] =
    array(
        'name'  => 'GeForce',
        'value' => '99.99'
    );
How to&Answers:

No, it’s not. Space symbol in programming doesn’t really have a special meaning. Symbols enclosed in quotes and thus forming a string can be used as associative array keys.

In fact, there are a lot of times when using such keys for associative arrays will make your code readable and handy to make changes to it.

$scores = array("John Doe" => 100, "Ivan Ivanovich" => 75.3);

What I see is you trying to use array keys as an expression, which is REALLY bad practice. Things are meant for what they meant for. Use associative keys as associative keys.

Answer:

It will work and is not bad practice. The whitespace is just a regular char in the index string. No problem with this.

As in many programming situations the indexes you are using in an array are dynamically created, this is nessary. Indexes can be even binary strings. Check this example, typical situation. We want to remove duplicate lines from a file and print every line only once:

file.txt

hello world. 
foo bar
hello world
123

example.php

$printed = array(); 
foreach(file('file.txt') as $line) {
    if(isset($printed[$line])) {
        continue; // skip the line
    }

    echo $line;
    $printed[$line] = true; // line will contain spaces
}

Answer:

I don’t think spaces are a problem in keys, but I do think using equal signs seems awkward. Based on your code example, I don’t see why you wouldn’t just use 3 dimensions on your array like so:


$blockGroup['products']['complete'][] =
    array(
        'name' => 'GeForce',
        'value' => '99.99'
    );

I may be misunderstanding your situation, but that seems more logical to me.

Answer:

Answering your original question, associated arrays in PHP map keys to values. In this case the keys you’re using are strings, that’s all PHP cares about in this case, not necessarily the contents of those strings (i.e. that they may or may not have spaces). I say this since you seemed unsure as to whether or not it is legal in the language (and not just whether or not it was bad practice).

As to whether or not it’s bad practice, it’s not one that I know of. It depends on the context, if that kind of key maps naturally to the value you want to store then it should be fine.

Answer:

It’s valid syntax, but it might be a better way to achieve whatever you’re trying to do.

Arrays can have Integer, FLoating, Null, Bool and String keys.

In the case of strings, PHP represent them internally as a sequence of bytes, so to my knowledge there’s no chance for introducing a vulnerability by using spaces or special characters for your keys.

However, in my opinion it makes the code less readable and more prone to mistakes by incorrectly typing a key, and spend countless hours to find out that you were supposed to type

$myKey['name=guitar price=200.00']

instead of:

$myKey['name=gutiar price=200.00']

the PHP manual page gives a thorough explanation of why this is a bad practice:

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

http://php.net/manual/en/language.types.array.php

Answer:

I’d say yes, it’s bad practice but it will work. Whatever you’re trying to achieve can be done a different way. May I suggest a multidimensional array? Or maybe a key and a value?

I imagine something like this could cause headaches down the road. More room for spelling mistakes IMO. Plus it’s not very nice to look at.

Keep in mind I’m specifically referring to your example. Something along these lines is fine:

array('toaster oven' => 100, 'heater' => 50);

Answer:

In regards to best practice, readability and practicality should be the main concern. If spaces in array keys make the code readable then feel free to use them. This entire post can be used as an array key, but it would not be practical.

I would not advise using spaces if you intend to create variable variables, using the array keys as variable names – the same goes for using extract(). This can be dangerous when used with data out of your control, such as user input, so be careful.

Spaces can still be used if you intend to create variable variables, just convert the spaces to underscores beforehand.

Source for variable variables: https://www.php.net/manual/en/language.variables.variable.php

Source for extract(): https://www.php.net/manual/en/function.extract.php