doubledee Posted March 8, 2012 Share Posted March 8, 2012 Why doesn't this code work... echo '<p>time() = ' . time() . ' seconds</p>'; echo '<p>$lastActivity = ' . $lastActivity . '</p>'; echo '<p>Seconds Active: ' . time() - $lastActivity . ' seconds</p>'; ...where $lastActivity comes from my database. When I run my script I see... time() = 1331187131 seconds $lastActivity = 1331186745 -1331186745 seconds The last line is dropping the label and there is now Date Math?! Debbie Quote Link to comment https://forums.phpfreaks.com/topic/258509-subtracting-two-unix-timestamps/ Share on other sites More sharing options...
Pikachu2000 Posted March 8, 2012 Share Posted March 8, 2012 Enclose the mathematical operation in parentheses, or perform it first, assign the result to a variable, then echo the variable. Quote Link to comment https://forums.phpfreaks.com/topic/258509-subtracting-two-unix-timestamps/#findComment-1325122 Share on other sites More sharing options...
doubledee Posted March 8, 2012 Author Share Posted March 8, 2012 Enclose the mathematical operation in parentheses, or perform it first, assign the result to a variable, then echo the variable. You're da man!! Thanks! So why do you have to do it that way? Debbie Quote Link to comment https://forums.phpfreaks.com/topic/258509-subtracting-two-unix-timestamps/#findComment-1325123 Share on other sites More sharing options...
kicken Posted March 8, 2012 Share Posted March 8, 2012 Because of Operator Precedence. The . (concatenation) and - (subtraction) operators have the same precedence level and are processed from left-to-right, so when php sees that line it does these steps: (assume time() returns 1234567 and $lastActivity contains 654321) '<p>Seconds Active: ' . time() Result: ''<p>Seconds Active: 1234567 ' [*]''<p>Seconds Active: 1234567 ' - $lastActivity Result: -654321 [*] -654321 . ' seconds</p>' Result: '-654321 seconds</p>' By either enclosing the math operation in parenthesis or moving it out to it's own line and saving the result to a variable, you force that to come first before the concatenation operations. Quote Link to comment https://forums.phpfreaks.com/topic/258509-subtracting-two-unix-timestamps/#findComment-1325129 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.