What is the real code for the age stamp?

TSFI
By TSFI

Now I'm really getting that frustated, angry and sad, I just searched in google for the search key "php calculate age", I get tons of sites which show that thing, I put those codes on output/datepicker.php, but you now what I am really getting?! THIS ERROR OF COURSE:

"Cannot redeclare getAge().."

I don't understand what the heck is wrong with that code, because I am doing it right, but that file doesn't want to accept it. WHY?! The php is indeed a B***h

  • Does the error message say where the function has been declared before? This would show that a funtion with the same name has been included elsewhere.

    Or you might have forgotten to add some bracket, i.e. { or } at some line in the code. This could result in the php interpreter not being able to process your code.

    If your code is not too long you could post it here. Maybe someone will notice the error in the code then.

  • TSFI

    @iionly: I used this which is on your given link also:

     

    <?php

    /*** make sure this is set ***/
    date_default_timezone_set('Europe/London'
    );

    /**
    *
    * Get the age of a person in years at a given time
    *
    * @param int $dob Date Of Birth
    * @param int $tdate The Target Date
    * @return int The number of years
    *
    */
    function getAge( $dob, $tdate
    )
    {
    $age = 0
    ;
    while(
    $tdate > $dob = strtotime('+1 year', $dob
    ))
    {
    ++
    $age
    ;
    }
    return
    $age
    ;
    }
    ?>

  • TSFI

    but actually I changed that code to this, which works fine, but the only problem is that in the age field is shows as the current year. Anything I have to fix in this so it shows the person's age, not the current year?:

         //date in mm/dd/yyyy format; or it can be in other formats as well
     
         $birthDate = "$day/$month/$year"; 

         //explode the date to get month, day and year 

         $birthDate = explode("/", $birthDate);
     
         //get age from date or birthdate
     
         $age = (date("md", date("Y", mktime(0, 0, 0, $birthDate[1], $birthDate[0], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2] - 1)); 
         echo $age;

  • I think the problem here is that TSFI is declaring that function in a view, and that view can potentially be called mulitple times which then causes the redeclaration error.

     

    Here's what you do:

    Add your function to start.php, or a file that's included in start.php (I usually have a functions.php file I use for declaring functions to keep things organized).

    Then in the view, you can use that function to do the calculation.