Re: Array functions with strict comparison

From: Date: Sat, 11 Nov 2023 19:43:00 +0000
Subject: Re: Array functions with strict comparison
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-121659@lists.php.net to get a copy of this message
Hello David, On Sat, 11 Nov 2023 at 20:04, David Gebler <davidgebler@gmail.com> wrote: > > On Sat, Nov 11, 2023 at 6:05 PM Andreas Hennings <andreas@dqxtech..net> > wrote: > > > Hello internals, > > I noticed that array functions like array_diff(), array_intersect() > > etc use weak comparison. > > > > > That's not quite correct. Using the example of array_diff, the comparison > is a strict equality check on a string cast of the values. So > array_diff([""], [false]) will indeed be empty > but array_diff(["0"],[false]) will return ["0"]. Thanks, good to know! So in other words, it is still some kind of weak comparison, but with different casting rules than '=='. Still this is not desirable in many cases. > > Tbh any use case for whatever array function but with strict comparison is > such an easy thing to implement in userland[1] I'm not bothered about > supporting it in core. But that's just me. I don't generally like the idea > of adding new array_* or str_* functions to the global namespace without > very good cause. There is a precedent for it though, in terms of changes > which have gone through in PHP 8, such as array_is_list or str_starts_with. I would argue that the strict variants of these functions would be about as useful as the non-strict ones. Or in my opinion, they would become preferable over the old functions for most use cases. In other words, we could say the old/existing functions should not have been added to the language. (of course this does not mean we can or should remove them now) Regarding performance, I measure something like factor 2 for a diff of range(0, 500) minus [5], comparing array_diff() vs array_diff_strict() as proposed here. So for large arrays or repeated calls it does make a difference. Regarding the cost of more native functions: Is the concern more about polluting the global namespace, or about adding more functions that need to be maintained? I can see both arguments, but I don't have a clear opinion how these costs should be weighed. Cheers Andreas > > [1] Example: > > function array_diff_strict(array $array1, array ...$arrays): array > { > $diff = []; > foreach ($array1 as $value) { > $found = false; > foreach ($arrays as $array) { > if (in_array($value, $array, true)) { > $found = true; > break; > } > } > if (!$found) { > $diff[] = $value; > } > } > return $diff; > }

« previous php.internals (#121659) next »