Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
A confusion about time() function in PHP

I cannot understand why the result of subtracting the current time from the variable of $_session['now'] that has included the previous time is zero.


I expected outputting the difference between the current time and the time when i have created the variable $student->now. Explain me please.

class Student
{

    public function __set($key, $value)
    {
        $_SESSION[$key] = $value ;
    }


    public function __get($key)
    {
        return $_SESSION[$key];

    }

}
session_start();

$student = new Student() ;

//__set function will be called ;
$student->now = time();


//__get function will be called ;
echo time() - $_SESSION["now"]; // output is zero ?!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

time() has a precision of ONE second, you are basically doing:


$now = time(); // e.g. 1627385278

echo time() - $now; // 1627385278 - 1627385278

This happens very fast, so the output is (almost always) zero.

The fact that your example code involves a "session" hints that you want to measure time between different HTTP requests. If that is the case, some logic is needed to ONLY set the stored value for the first time, but not thereafter.

over 4 years ago · Santiago Trujillo Report

0

The $_session['now'] variable is set in the line before the echo. In the echo line the current time is compared to the time set in the line before.

Because both lines are executed directly after each other, both are executed within the same second. There will be a difference of milliseconds but time() function is measured in seconds, refer to: https://www.php.net/manual/en/function.time.php.

That's why both timestamps are the same and there is no difference between these when comparing them.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!