0

In c# you can do ?? to check for null and then use a value like so..

DateTime? today = null;
DateTime todayNotNull = today ?? Date.Now;

Is there a shorthand way to do this in PHP?

3 Answers 3

3

Yes.

$var = ConditionalTest ? ValueIfTrue : ValueIfFalse;

Note that both ValueIfTrue and ValueIfFalse must be used.


In your specific case:

<?php
    $today = null;
    $todayNotNull = isset($today) ? $today : date();
?>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the Ternary operator as indicated by other users.

$today = null;
$todayNotNull = $today ? $today : time();

As of PHP 5.3, you can also shorten this to the familiar syntax you want:

$todayNotNull = $today ?: time();

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Comments

0
$todayNotNull = ($today===NULL ? date() : $today);

UPDATE: Be careful when using implicit NULL check like $today ? $today : date().

true is true. (type: boolean)
false is false. (type: boolean)
null is false. (type: NULL)
[] is false. (type: array)
[0] is true. (type: array)
[1, 2, 3] is true. (type: array)
{1: 2, "x": 3} is true. (type: array)
"" is false. (type: string)
"0" is false. (type: string)
"1" is true. (type: string)
"2" is true. (type: string)
"x" is true. (type: string)
0 is false. (type: integer)
1 is true. (type: integer)
2 is true. (type: integer)
0 is false. (type: double)
0.1 is true. (type: double)
0.2 is true. (type: double)

I rather urge you to explicitly test for NULL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.