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

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

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

Will foreach work if executed as:

foreach(arr_name as $key => $value) 

for keys that are non-numeric?

-2
source share
3 answers

Yes, foreach supports any type of key. In your case, $key will be a string, 'eggs' and 'pencil' respectively for each element. In fact, foreach intended for use with arrays that have non-numeric keys, which you cannot easily iterate with for .

+4
source

Yes, PHP does not have a real difference between arrays with numeric and non-numeric keys. They are all just arrays related to PHP.

+3
source

Yes, the explanation given by BoltClock is correct, and I suggest you try it manually. You missed $ to the array name in the foreach statement

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

+1
source

All Articles