Home >Backend Development >PHP Tutorial >How Can I Accurately Calculate a Person's Age in PHP?

How Can I Accurately Calculate a Person's Age in PHP?

DDD
DDDOriginal
2024-12-19 14:55:11391browse

How Can I Accurately Calculate a Person's Age in PHP?

Calculating Age in PHP

Originally, the question centered around a faulty PHP script for calculating a person's age based on their date of birth (DOB) in the dd/mm/yyyy format. The issue with the provided function lay in an infinite while loop, raising concerns about reliability.

Fortunately, there is a more dependable approach to calculate age using PHP:

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>

In this script:

  • The input DOB is split into individual months, days, and years.
  • The mktime function converts the DOB into a Unix timestamp.
  • The date function is used to extract the month and day components from the current date.
  • The final age calculation ensures accuracy by considering both the difference in years and whether the person's birthday has passed in the current year.

This approach effectively calculates the age and avoids the infinite loop issue encountered in the previous function.

The above is the detailed content of How Can I Accurately Calculate a Person's Age in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn