简体   繁体   中英

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?

It's not clear what you intend to do with the array once it's assigned but in terms of correct PHP programming, eg 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 ''
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM