Home >Backend Development >PHP Tutorial >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:
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!