How to validate date of birth today & get the age from the birthday using php

we have already explained how you can get age from provide date now will focus more on how to validate date of birth today

now this function is basically validate date and finds the age from date_diff function in php

We are going to use the function we applied in date validation in How to do date validation in php (special function)

The simple function that does the work

then we apply a little tweak to get what we want
this function makes sure that the date parameters are integers

 <?php 
function 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[0];
	$month = $dateparameters[1];
	$actualmonth = $dateparameters[1];
	$actualday = $dateparameters[2];
	$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 actual month and day is in range of days that should be in the provided month of the given year
		$origin = date_create($actualdate); // create the date of birth in proper date parameters
		$target = date_create(date('Y-m-d')); // creates the current day from the user is calculating from
		$age = date_diff($target, $origin);
		$age = intval($age->format('%y'));
	}
		
	}
return $age;
}
?>

HOW TO APPLY IT

let’s apply this in our work

you can echo this function since it just integer that is expected from it

we can still program a logic to check if it empty or not

 
<?php
$birthdate = '2016-10-29';
if(!empty(get_age($birthdate))){
	echo 'since you are born in '.$birthdate.' your age is: <b>'. get_age($birthdate).' years</b> Older';
}else{
	echo $birthdate.' is invalid date of birth';
}
?>

Related

How TO create a Login Form (w3schools vs bootstrap)

Every transactional website should have a login form that...

Best PHP checkdate alternative: How to do date validation in php (exclusive)

this checkdate alternative special function validates date in such...

How to use php to check age for birthday messages

We going to check age for birthday messages using...

How to check product expiration duration of any product using php (2 proven function)

with this simple php trick you can check expiration...

the 2 easy ways to create dynamic form inputs in php

these are 2 ways you can create dynamic form...