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? php php

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


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.


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 barhello world123

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}


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.