Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda