php

PHP - Assign a value to a variable only if it's not false


I would like to know if there is a more simple way to assign a value to my variable :

$foo = bar($baz);      // 'NULL' or '0' or '1' or '2' or ...
$foo = $foo ?: 0;     // '0' or '1' or '2' or ...

My problem is that $foo can be either NULL or a positive integer, including 0.

I want it to become 0 if its value is NULL, and to keep its value if it is not.

Thanks for your answers.

EDIT

I cannot merge the 2 lines so my question is only for the second one.


Solution

  • Try this ;)

    $foo = intval( $foo );