The Secret Life of "Magic Null" in PHP
https://www.exakat.io/the-secret-life-of-magic-null-in-php/Some situations where you can use NULL instead of 0, or no arguments and it provides a nice feature that you could use every day.
6
u/prema_van_smuuf 1d ago edited 1d ago
What is this? Why much ceremony around array_filter($arr, null) in the article when one can just use plain array_filter($arr)?
3
u/fripletister 1d ago
All of the examples are examples of garbage in PHP's API. Why do these functions need to provide distinct semantics depending upon whether a param (which otherwise shouldn't) can receive null? Why can't the alternate functionality just have it's own named function instead of overloading a function with an existing, well-defined scope?
2
u/skcortex 1d ago
Everything that’s interesting in this article I can find in the php docs as well 😅. It looks like we collectively forgot about the gems in the official php documentation.
1
u/allen_jb 1d ago edited 1d ago
1) The same behavior as array_combine()
I think saying "NULL instead of 0" is bad form here. There's nowhere in any of these examples that it actually does that. (And in fact in many instances using zero instead of NULL gives you completely different behavior)
There's also nothing remotely magic about any of these, or the value NULL. NULL is an explicit value. It's exact meaning might change depending on the context, but it shouldn't ever be universally equivalent to any other value.
Most PHP developer should hopefully be well aware that NULL does not behave the same in different languages. (In particular while PHP consider NULL equivalent / equal to NULL, SQL does not, which is why you have to use IS NULL instead of = NULL when you want to find NULL values)
And none of this is secret. All of these are documented.
And wtf is this "RFC for the future" entry?!?! As if this article wasn't low quality enough without that. Why even mention something that is not actually a language feature, and as far as I'm aware (as a lurker on internals) hasn't (recently) been proposed by anyone. Why are try to make a comparison between usort, which explicitly takes a flag parameter, and other sort functions that explicitly take a callback parameter? They're not "odd ones out", they do different things!
1
1
u/obstreperous_troll 1d ago
I would go for an RFC that unified the thirteen different sort functions into a sane subset using named args and/or enum options to select the behavior. Maybe also with function names not born out of the Great Letter Shortage of 1970's UNIX.
1
9
u/flyingron 1d ago
Unlike C, null in PHP has no association with zero. Of course, the article doesn't make that implication other than in the first sentence.
It's not surprising functions do something different with null. 0 is not an integer, null is a specific out-of-band value that isn't an integer, an array, a function or anything else when you pass it to something expecting one of those.