Objects As Keys In Foreach

<?php

// Weakmaps accepts objects and arrays as keys
$source = new Weakmap();
$key = (object) ['a' => 2];
$source[$key] = 1;

// Yield may emit objects and arrays as keys
$source = function () {
    yield (object) ['a' => 3] => 1;
};
// This is just for illustration
$source = $source();

// An iterator may return objects and arrays as keys(mixed, in fact)
class myIterator implements Iterator {
    private int $position = 0;

    public function rewind(): void { $this->position = 0; }
    public function current(): mixed { return 1; }
    public function key(): mixed {
        return (object) ['a' => 4];
    }
    public function next(): void { ++$this->position; }
    public function valid(): bool { return $this->position == 0; }
}
$source = new myIterator();

foreach($source as $key => $value) {
    print get_class($key); // Stdclass
    print $value;        // 1
}

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

Last updated: 16 July 2026