-3

How can I get the function strtotime() to return 0 if the argument is also 0?

In my example, $testvar2 returns "empty".

$testvar = 0;
$testvar2 = strtotime($testvar);

print_r($testvar2);
Rizier123
  • 58,877
  • 16
  • 101
  • 156
MeTa
  • 89
  • 1
  • 3
  • 11

5 Answers5

4

Its not returning empty its returning you bool(false). Check with var_dump instead of print_r.

Workaround:

$testvar2 = ($testvar) ? strtotime($testvar) : 0;
Rikesh
  • 26,156
  • 14
  • 79
  • 87
3

Just simply make a ternary operator, since strtotime() will return false if it fails you can simply return 0 otherwise it will return the correct value.

$testvar2 = strtotime($testvar)?:0;
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

Simply add a check for that variable(0, false, null, not set etc.). Try with -

$testvar2= (!empty($testvar)) ? strtotime($testvar) : 0;
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0
function getTime($testvar){
    return ($testvar == 0)? 0 : strtotime($testvar);
}
Shoaib Rehan
  • 526
  • 6
  • 16
-1
public static function myStrToTime($var=null)
{
    if($var)
        return strtotime($var);
    return 0;
}

No offense, but maybe you should look up some more tutorials on PHP. :)

FrozenDroid
  • 166
  • 13