Please disable your ad blocker.
The only ads on this site are discreet (sidebar on desktop, below the content on mobile).They do not interfere with reading and may even offer you benefits (discounts, free months…).
PHP: calculate age from a date of birth, without a database
Difficulty
Displaying age based on a date of birth is a common requirement on websites, whether for user profiles, birthdays, or other use cases.
This tutorial shows you how to do it easily in PHP, without needing a database, using a reusable function. Ready to learn how?
Place this first block of code right after the <body> tag:
<?php function Age($birth_date) {
$arr1 = explode('-', $birth_date);
$arr2 = explode('-', date('Y-m-d'));
if(($arr1[1] < $arr2[1]) || (($arr1[1] == $arr2[1]) && ($arr1[2] <= $arr2[2])))
return $arr2[0] - $arr1[0];
return $arr2[0] - $arr1[0] - 1;
}
?>
Place this second block of code where you want the age to be displayed:
<?php $my_birthday = '1992-07-19';
$my_age = Age($my_birthday);
echo $my_age;
?>
For this example, the date of birth is 1992-07-19 (no, it’s not mine 😉). Here is the result: 33.
If you want to display multiple ages on the same page, simply paste the second block of code multiple times and change the date of birth.
Comments