Thursday 13 December 2012

Calculate Age from Birth Year via PHP

If you have a system where you need to calculate the actual age of your users from their year of birth, this tutorial brings an end to such problems. 
The tutorial helps you to calculate the age of a user from a given year of birth. To calculate the age of a single user, just pass the year of birth of that user to the below function to output the user's age on the screen.
To calculate the ages of multiple users, simply pass the ages of these users in a while loop based on the year of birth of these users from your database etc, to the below function to output their ages on the screen.
Below is the age calculation function and an example of how to pass a user's year of birth to the function and display it on the screen.

Code:
<?php
$years = "1985"//Assigned year of birth - This is the area you can pass your user's birth year
function calculateAge($birthdate)
{
      return floor((time() - strtotime($birthdate))/31556926); 
}
print calculateAge($years)." year(s)"//This one displays the user's actual age
?>



No comments:

Post a Comment