On 25 March 2025 16:42:45 GMT, Robert Chapin <p...@miqrogroove.com> wrote:
>On 3/25/2025 4:45 AM, Rowan Tommins [IMSoP] wrote:

>> The implied default in the first is 'off', but in the second it's 'on'.
>I thought the implied default was null.


By "implied", I'm talking about the observed behaviour: if you give it null, 
does it *act the same as* when you give it 'off', or when you give it 'on'?



>>> A different example could be if (coalesce($_POST['tick']) > 10) return;
>> In this case, the implied default is 0.
>
>I thought the implied default was null. 


In this case it's more than implied, the engine is literally converting the 
value to zero.

The logical answer to the question "is null greater than ten?" is "null", as 
used by SQL. e.g. 

- "I don't know how many apples are in the box." (set num_apples=null)
 - "Are there more than ten apples in the box?" (query: num_apples>10)
- "I don't know." (result: null)

The reason you don't get that answer in PHP is that it looks at the context and 
"type juggles" the null to an integer, and gives you the answer to "is zero 
greater than ten?" instead.

(In this specific case, you can't observe the difference, because null would 
itself be juggled to false by the if statement; but substitute "less than ten", 
and you get true in PHP, still null in SQL.)


Using coalesce($foo) in this example means the reader has to remember or guess 
the type juggling rules to know that it's equivalent to (int)($foo ?? null), 
and that (int)null will give 0.

Writing coalesce($foo, 0) or ($foo ?? 0) is a small cost when writing the code 
to save cost every time anyone reads it.


Rowan Tommins
[IMSoP]

Reply via email to