update page now
PHP 8.5.6 Released!

Voting

: three plus five?
(Example: nine)

The Note You're Voting On

tasiot
3 years ago
array_unique is not compatible with php 8.1 enums because enums don't have a string representation yet (even the BackedEnum of string type…).
You get an error: "Object of class XXXX could not be converted to string."

So I wrote this function that creates a string representation of the enums and use the array keys to remove duplicates:

<?php

function array_unique_81(array $values): array
{
    $unique = [];
    foreach ($values as $value) {
        if ($value instanceof \UnitEnum) {
            $key = 'e:' . \get_class($value) . ':' . $value->name;
        } else {
            $key = 's:' . (string)$value;
        }
        $unique[$key] = $value;
    }
    return \array_values($unique);
}

?>

<< Back to user notes page

To Top