Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13948

Accessing an element in an array by key

Today in a code audit, it was pointed out, that accessing a variable element like $array['keyname'] is not an optimum way to do it and instead a constant should be defined and then used as below.

define('KEYNAME', 'keyname'); // Constant defined somewhere centrally

$array[KEYNAME]; // actual usage

My question is, is that notion correct? And this is stemming from the tool Sonarqube.

enter image description here

Upvotes: 1

Views: 230

Answers (1)

Jesse Rushlow
Jesse Rushlow

Reputation: 196

If you were only accessing the array value by key once, then $array[‘key’] would be sufficient. But if you are accessing the value more than once, $array[self::CONSTANT] would keep your code DRYish.

If the key were dynamic, then obviously a constant wouldn’t be appropriate. Instead, using a property would have the same result. I.e. $array[$this->property]

Upvotes: 3

Related Questions