Enum could not be converted to string with \array_intersect
Description
The following code:
<?php
class EnumTest extends Unit
{
public function testArrayIntersect(): void
{
$array1 = [TestEnum::TEST];
$array2 = [TestEnum::TEST];
$actual = \array_intersect($array1, $array2);
self::assertCount(1, $actual);
}
}
enum TestEnum {
case TEST;
}
Resulted in this output:
Object of class TestEnum could not be converted to string
But I expected the test to pass and internally \array_intersect to be able to work with enums. The same goes for \array_diff as well, so most probably other array functions, too
PHP Version
PHP 8.1.0
Operating System
php:8.1-fpm-buster
That comes down to how array_intersect works.
https://www.php.net/manual/en/function.array-intersect.php
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
array_intersect will also not work for other objects that don't implement __toString and it might unintentionally match objects that coincidentally return the same string. I think at this point we'd be better off adding a new array_intersect alternative that uses strict comparison instead.
Any change here will likely require an RFC.
Related is that there was a deliberate decision to not support automatically converting backed enums to their backed type for the time being. As mentioned, implementing that will come in a future RFC after enums have settled into common usage.
I think at this point we'd be better off adding a new
array_intersectalternative that uses strict comparison instead.
Sorting would still be required to reach O(n log n) efficiency that the various array comparison functions offer. Using only equality would mean settling for the naive O(n^2) algorithm - which could also be trivially implemented in userland if there was a need to work with arrays containing unsortable items like enums.
Now, what to do with this issue? I'm not sure. On the old tracker I'd resolve as Suspended, but those did have a tendency to get lost and forgotten over time. At the very least this isn't actionable now or in the foreseeable future, and there is the fact that array_intersect and enums are actually behaving as intended...
For the reasons stated by @damianwadley I'll close the issue. array_intersection is working as documented, for better or worse. I personally am in favor of a more complete standard library but not all core members are. In any case, this would require an RFC.
Still hoping this becomes possible in the future 🤞 but I understand why it's not yet.