Indexing a PHP array of objects by their class name
Published on 2023-06-17 • Modified on 2023-06-17
This snippet shows how to index a PHP array of objects by their class name. We can use the array_reduce
function instead of doing a loop. Note that you can only do this if you are sure you don't have several objects of the same class. To be sure it's not the case, you can verify that the count is identical for both arrays.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
use App\Samples\OrderPlacedEvent;
use App\Samples\ProductSample;
use App\Samples\SortableObject;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet261Trait
{
public function snippet261(): void
{
$objects = [
new ProductSample(),
new OrderPlacedEvent(),
new SortableObject('foo'),
// new SortableObject('bar'),
];
var_dump($objects);
$indexedByClass = array_reduce($objects, static function ($carry, $item) {
$carry[\get_class($item)] = $item; // @phpstan-ignore-line
return $carry;
}, []);
var_dump($indexedByClass);
var_dump($indexedByClass[OrderPlacedEvent::class]);
if (\count($objects) === \count($indexedByClass)) {
echo PHP_EOL."The array doesn't contain duplicates of the same class.";
}
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉