lookingGlass
lookingGlass

Reputation: 365

PHP associative array some will only have a key

If I need an associative array, but I only need the key for most of the values. Do I need to still need to set a value for the things I wont be using for example:

$car_info = array(
  'toyota' => array(
    'description' => 'toyota Description',
   ),
  'ford' => array(
   'description' => 'ford Description',
  ),
  'bmw' => array(
  ),
  'subaru' => array(
  )
)

Can I leave 'description' out or should I set it to an empty value?

Upvotes: 1

Views: 38

Answers (1)

Technoh
Technoh

Reputation: 1600

It's not clear what you intend to do with the array once it's assigned but in terms of correct PHP programming, e.g. no error reported, you can definitely leave it as it is. You could even assign an empty string or null to the keys you want, although I'm not sure what would be the point of it. Something like:

$car_info = array(
    'toyota' => array(
        'description' => 'toyota Description',
    ),
    'ford' => array(
        'description' => 'ford Description',
    ),
    'bmw' => null, // or ''
    'subaru' => null, // or ''
)

Upvotes: 1

Related Questions