PHP is Fun!

Just another WordPress.com weblog

Get current age based on birthdate

leave a comment »

I wrote a quick little function that simply returns a persons current age by inputting their birthday as a DATE (YYYY-MM-DD).

If you want to use the function, go ahead, but please leave a comment! If you find a way to shorten it or make it run faster, please let me know! I’m always open to new ways of doing things, especially faster/more efficient ways.


function get_current_age($bday)
{
	/* Calculates current age. $bday must be in DATE format
	(YYYY-MM-DD). Returns false if $bday is not the right
	format OR if it is in the future */
	if (!ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $bday)) {
		return false;
	}
	$cy = date('Y');
	$cm = date('n');
	$cd = date('j');
	$bday = explode("-",$bday);
	$yob = $bday[0];
	$mob = ltrim($bday[1],"0"); // remove leading zero
	$dob = ltrim($bday[2],"0"); // remove leading zero

	$age = $cy - $yob;
	if ($cm < $mob) {
		$age--;
	}
	else if ($cm == $mob) {
		if ($cd < $dob) {
			$age--;
		}
	}

	if ($age >= 0) {
		return $age;
	}
	else {
		return false;
	}
}

Written by nicholasarnold

March 30, 2008 at 5:58 am