Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Trevor Wood
Trevor Wood
17,828 Points

How does this PHP function work?

I just found this really nice php function to display strtotime in seconds,minutes,hours etc. But I haven't a clue how it works, there's quite a few operaters in use in an order that I haven't seen before.

Could somebody with a little more knowledge in php break this down for me? namely the "for" conditions and the $print variable.

<?php
function time_since($since) {
  $chunks = array(
    array(60 * 60 * 24 * 365 , 'year'),
    array(60 * 60 * 24 * 30 , 'month'),
    array(60 * 60 * 24 * 7, 'week'),
    array(60 * 60 * 24 , 'day'),
    array(60 * 60 , 'hour'),
    array(60 , 'minute'),
    array(1 , 'second')
  );

  for ($i = 0, $j = count($chunks); $i < $j; $i++) {
    $seconds = $chunks[$i][0];
    $name = $chunks[$i][1];
    if (($count = floor($since / $seconds)) != 0) {
      break;
    }
  }

  $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  return $print;
}
?>

1 Answer

Gergő Bogdán
Gergő Bogdán
6,664 Points

Related to the $print variable, the ternary operator (? :) is quite common in C syntax based languages see details for PHP, but basically its the same as the code below, only in one line.

if($count==1) {
    $print='1 '.$name;
}
else {
    $print="$count {$name}s"
}

Related to the for cycle, it would be great if you could debug it, so you understand the logic. If you cannot debug it on a computer try to take a sheet of paper and write down the steps with an example value, that will surely help you understand the algorithm.

Trevor Wood
Trevor Wood
17,828 Points

Thanks bud, I've seen them before but haven't really understood them or been able to google them (don't know what it's called).

What's tripping me up on the for part is the commas and semicolons inside of the conditional. I've never seen them used on the inside and am unsure what they do.