NotionCommotion Posted November 17, 2016 Share Posted November 17, 2016 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 Quote Link to comment https://forums.phpfreaks.com/topic/302554-arithmetic-and-null/ Share on other sites More sharing options...
Solution Jacques1 Posted November 17, 2016 Solution Share Posted November 17, 2016 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. Quote Link to comment https://forums.phpfreaks.com/topic/302554-arithmetic-and-null/#findComment-1539403 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.