Objects As Keys In Foreach

../_images/objects_as_keys.png

foreach() usually works on arrays, where the keys are either integer or strings. Not null, boolean anymore, but, more importantly, no array or objects. Yet, there are three solutions to make an object appear as the key, instead of the value (or also as the value).

The first option is to use a Weakmap object, which uses the array syntax, and accepts anything as keys.

Then, you can use a generator, yield``ing any type on the ``=> operators, left and right. Note that it won’t work with yield from which requires an array.

Finally, you can use an interator, which has a dedicated method key, with a return type of mixed.

While it is not common in PHP, there are other languages which accepts such structures, and may hand it to PHP for further processing.

See Also

PHP Error Messages

PHP Features