Does foreach() work for non-numerical array keys?

后端 未结 3 1053
春和景丽
春和景丽 2021-01-29 12:03

I was wondering if foreach() works when the array looks like this:

  • arr_name[eggs] = something
  • arr_name[pencil] = something else

Will foreac

相关标签:
3条回答
  • 2021-01-29 12:21

    Yes, foreach supports any kind of key. In your case, $key will be a string, 'eggs' and 'pencil' respectively for each item. In fact, foreach was intended for use with arrays that have non-numerical keys which you can't easily iterate using for.

    0 讨论(0)
  • 2021-01-29 12:43

    Yes, PHP has no real distinction between arrays with numeric vs non-numeric keys. They're all simply arrays as far as PHP is concerned.

    0 讨论(0)
  • 2021-01-29 12:44

    Yes the explanation given by BoltClock is right & i would suggest you to manually try too. You have missed $before array name in the foreach statement

    foreach($arr_name as $key=>$value) echo $value ?>

    0 讨论(0)
提交回复
热议问题