pepe
pepe

Reputation: 9909

PHP function running inside loop not working (with code)

I am running this function

function Age($month, $day, $year) {
    date_default_timezone_set('America/New_York');
    $dob = $month .''. $day .''. $year;
    $startDate = strtotime($dob);
    $endDate = time();
    $dif = $endDate - $startDate;

    return $years = (date('Y', $dif) - 1970) .' y, '. ($months = date('n', $dif) - 1).' m';
}

inside a foreach loop (some CodeIgniter markup):

foreach ($users as $row) {
    echo $this->includes->Age($row->birth_month, $row->birth_day, $row->birth_year)
  }

The loop works OK, showing all my users.

But the problem is that it calculates the age correctly for the first user and then shows that same age for all other users. I should point out that all other user's data is correct, only the age is wrong.

Anyone know how to fix this?

Thanks!

Upvotes: 1

Views: 540

Answers (3)

user635913
user635913

Reputation: 11

You're missing space/separators.

$dob = $month .''. $day .''. $year;

should be

$dob = $month .'/'. $day .'/'. $year;

edit: Ambiguity. If using mm-dd-yyyy format, should be /

. and - indicate dd-mm-yyyy

Upvotes: 1

Shad
Shad

Reputation: 15451

Your $dob looks malformed. Try $dob = $year . '-' . $month . '-' $day;

Upvotes: 3

azat
azat

Reputation: 3565

Maybe CI is caching the result?
Seems that function Age is correct

Upvotes: 0

Related Questions