note 127958 added to function.array-unique

From: Date: Wed, 23 Nov 2022 22:45:51 +0000
Subject: note 127958 added to function.array-unique
Groups: php.notes 
Request: Send a blank email to php-notes+get-219913@lists.php.net to get a copy of this message
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); } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.159.161 (proxied: 2a01:e0a:a9c:1ca0:e487:d8b5:23a0:e485) ---- Manual Page -- https://php.net/manual/en/function.array-unique.php Edit -- https://main.php.net/note/edit/127958 Del: integrated -- https://main.php.net/note/delete/127958/integrated Del: useless -- https://main.php.net/note/delete/127958/useless Del: bad code -- https://main.php.net/note/delete/127958/bad+code Del: spam -- https://main.php.net/note/delete/127958/spam Del: non-english -- https://main.php.net/note/delete/127958/non-english Del: in docs -- https://main.php.net/note/delete/127958/in+docs Del: other reasons-- https://main.php.net/note/delete/127958 Reject -- https://main.php.net/note/reject/127958 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219913) next »