Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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'
    );
like image 506
Marcio Mazzucato Avatar asked Apr 24 '13 02:04

Marcio Mazzucato


People also ask

Which one is correct syntax of associative array in PHP?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.

Are PHP arrays associative or integer indexed?

There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables.

Are PHP associative arrays ordered?

An array in PHP is actually an ordered map. So yes, they are always ordered.


1 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.

like image 135
Nemoden Avatar answered Nov 06 '22 11:11

Nemoden