PHP Get Age Function
Posted on February 5, 2008 in Tutorial | 4 Comments »
Such things like copyright dates, ages, etc. can cause problems on websites unless they are dynamic. For example, I have my age in the little about me blurb in the sidebar. I made a little function to calculate my age so that I don’t have to go in every year on my birthday and add another year to my age.
The Function
function age($bMonth,$bDay,$bYear) {
$cMonth = date('n');
$cDay = date('j');
$cYear = date('Y');
if(($cMonth >= $bMonth && $cDay >= $bDay) || ($cMonth > $bMonth)) {
return ($cYear - $bYear);
} else {
return ($cYear - $bYear - 1);
}
}
This function takes 3 arguments: the birth month, the birth day, and the birth year. It will return the calculated age. It obviously won’t work with an age in the future; it will return a negative number. I could add in checking to see if it’s a valid date, but I don’t think it’s really necessary.
Nothing too complicated. Let me know if anyone has any suggestions to shorten the code.

























KaimiteMarch 10, 2008 at 5:36 am
Hello :
Here is 2 suggestions :
OR
See you.
Kaimite
Sony AKJune 19, 2008 at 3:22 am
Great post :) i’m using it :)
Matthew PennellJune 21, 2008 at 10:45 am
Sorry for the much delayed comment, but how about this much simpler solution:
echo intval((time() - strtotime(‘14-01-1978’)) / 31557600);
It will tick over at some point during the day of your birthday, as it uses an approximation of a year (365.25 days to represent a partial leap-year).
How to take out user's AGE in PHP? - DesignersTalkSeptember 12, 2008 at 5:19 pm
[…] this PHP Get Age Function | Trevor Davis My-PHP.tk ••• Your Free PHP Resource! ••• […]