# Calculate Age in PHP

0
631

How to Validate Date of Birth and Calculate Age in PHP.

In a previous post, we discussed how to calculate age from a given date of birth in PHP. In this article, we’ll delve deeper into the process by focusing on how to validate the date of birth before calculating the age. We’ll also optimize the existing code and explore some additional ideas to enhance its functionality.

## Validating Date of Birth

Before calculating age, it’s crucial to ensure that the provided date of birth is valid. Let’s optimize the validation process with a simple and efficient PHP function.

``````<?php
function validate_date_and_get_age(\$date){
\$dateparameters = array();
\$date = preg_replace("/[^0-9\']/", ",", \$date);
\$date = explode(',', \$date);
\$age = '';
if(count(\$date) == 3){
for (\$i = 0; \$i < 3; ++\$i) {
\$dateparameters []= \$date[\$i];
}

\$year = \$dateparameters;
\$month = \$dateparameters;
\$actualmonth = \$dateparameters;
\$actualday = \$dateparameters;
\$actualdate = \$year.'-'.\$month.'-'.\$actualday;
\$day = cal_days_in_month(CAL_GREGORIAN, \$month, \$year);

\$day = range(1, \$day); // day range
\$month = range(1, 12); // month range

if(in_array(\$actualday, \$day) && in_array(\$actualmonth, \$month)){ // Check if the actual month and day are within the valid range
\$origin = date_create(\$actualdate); // Create the date of birth in proper date parameters
\$target = date_create(date('Y-m-d')); // Create the current date
\$age = date_diff(\$target, \$origin);
\$age = intval(\$age->format('%y'));
}
}
return \$age;
}
?>``````

## Applying the Function

Now that we have an improved validation function, let’s see how to apply it to calculate and display the age.

``````<?php
\$birthdate = '2016-10-29';
\$age = validate_date_and_get_age(\$birthdate);

if(!empty(\$age)){
echo 'Since you were born on '.\$birthdate.', your age is: <b>'.\$age.' years</b> old.';
} else {
echo \$birthdate.' is an invalid date of birth.';
}
?>``````