Friday, August 7, 2009

Calculating Age using Birthday in PHP

Here's some food for the thoughts: calculating age using birthday in PHP.


function getAge($birthday){
$dt = strtotime($birthday);
// convert the birthday to a standard format (UNIX epoch)
$a = gmdate('Y') - gmdate('Y',$dt);
// find the difference of years
return $a; // return the age.


And here we have, a simple Age calculating function which is useful when displaying age on User profiles or calculating age restriction and so on.

For example, you can put this against a movie age rating checker:

$bday = '1993-04-05';
$age = getAge($bday);

$movies = getPGMovies();

if($age >= 21){
// R21 and below can be watched
$movies= array_merge($movies,getR21Movies());
if($age >= 18){
// M18 and below can be watched
$movies= array_merge($movies,getM18Movies());
if($age >= 16){
// NC16 and below can be watched
$movies= array_merge($movies,getNC16Movies());
// display $movies

1 comment:

qwerty said...
This comment has been removed by the author.