0

Should be simple right? Well I've been at the PC for 16 hours so far and the answer is probably screaming at me in the face, but I can't hear it...

This code...

$differenceInSeconds = 448005;

if($differenceInSeconds >= "86400"){
    $calcDays = floor($differenceInSeconds / 86400);

    if($calcDays = "1"){
        $daysPlural = "day";
    }else{
        $daysPlural = "days";
    }

    $lastupdate = $calcDays." ".$daysPlural." ago";
}

echo $lastupdate;

Outputs this...

1 day ago

When it should output this...

5 days ago

Any ideas folks? Thanks,
Michael

Edited by happygeek: moved

5
Contributors
5
Replies
34
Views
3 Years
Discussion Span
Last Post by mmcdonald
1

try this i hope this work

<?php
$differenceInSeconds = 448005;

if($differenceInSeconds >= "86400"){
    $calcDays = floor($differenceInSeconds / 86400);
    //echo $calcDays;
    if($calcDays == "1"){
        $daysPlural = "day";
      //echo   $lastupdate = $calcDays." ".$daysPlural." ago";
    }else{
        $daysPlural = "days";
      //  echo $lastupdate = $calcDays." ".$daysPlural." ago";
    }

   $lastupdate = $calcDays." ".$daysPlural." ago";
}

echo $lastupdate;


?>
0

This is why I like using "Yoda Conditions". Even if you make mistakes like these, the variable isn't overwritten.

if ("1" = $calcDays")

This would result in an actual error being thrown, since you can't assign to a constant value like that.

Also, why are you quoting the numbers in the IF statements? It's entirely pointless, and just adds the need for PHP to cast them back to numbers to do the comparison.

And you should initialize $lastUpdate before the main IF statement, or in an ELSE clause. Otherwise if the difference is less than a day, it'll be undefined.

Edited by Atli: Forgot about the error in PHP for yoda conditions :P

0

Also I know this isn't important but perhaps you should remove the quotations from the integers/numbers to improve efficency. Comparing two numbers is a lot faster than comparing a number and a string because of the amount of bits stored and the conversion required by php. For example:

<?php
$differenceInSeconds = 448005;
if($differenceInSeconds >= 86400){
    $calcDays = floor($differenceInSeconds / 86400);
    //echo $calcDays;
    if($calcDays === 1){
        $daysPlural = "day";
      //echo   $lastupdate = $calcDays." ".$daysPlural." ago";
    }else{
        $daysPlural = "days";
      //  echo $lastupdate = $calcDays." ".$daysPlural." ago";
    }
   $lastupdate = $calcDays." ".$daysPlural." ago";
}
echo $lastupdate;

And note that the final php deliminator isn't required when dealing with a pure php page and will take off a few milliseconds off the page loading time.

Edited by cwarn23

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.