Jump to content

Arithmetic and NULL


NotionCommotion
Go to solution Solved by Jacques1,

Recommended Posts

For some reason, I though NULL and arithmetic resulted in NULL with PHP.  Maybe I was thinking JavaScript, so I tested it, but it was the same as PHP.  Then I tried MySQL, and found it was what I was thinking.  Glad I wasn't going totally crazy.

 

So....  Other than using a condition to check if null along with a ternary, what is the best way to return NULL if any of the arguments are NULL?

<?php
 
$x=null;
$y=1;
var_dump($x*$y);    //results in 0, but wanted NULL
var_dump($x+$y);    //results in 1, but wanted NULL
Link to comment
Share on other sites

  • Solution

Just don't. Don't rely on languages to guess what you mean when you juggle with nonsense values, and don't try to produce results from nonsense input.

 

I know this is hard to believe for a PHP programmer, but many languages actually trigger an error when the program does weird things like trying to calculate sums of void values. You should do that too, because it's the most straightforward reaction. If you absolutely must produce a result, then return immediately after validation. No magic.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.