开发者

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

开发者 https://www.devze.com 2023-01-29 00:40 出处:网络
I was wondering i开发者_JAVA百科f foreach() works when the array looks like this: arr_name[eggs] = something

I was wondering i开发者_JAVA百科f foreach() works when the array looks like this:

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

Will foreach work if run as:

foreach(arr_name as $key => $value)

for they keys that have a non-numerical value ?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消