time -> seconds to array(y,w,d,h,m,s)

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

time -> seconds to array(y,w,d,h,m,s)

Post by printf »

This is a simple 'seconds' to array ( years, weeks, days, hours, minutes, seconds )

weeks, days, hours, minutes, seconds <- 2 digit with leading zero!

Just pass the function a var with 'seconds'! The interesting thing is that it uses a loop with a single line of code to build the output array! Much different than using if and else!

Code: Select all

<? 

function tick_count ( $s )
{
	$out = array ();

	( int ) $time = array ( 'years' => 31536000, 'weeks' => 604800, 'days' => 86400, 'hours' => 3600, 'minutes' => 60, 'seconds' => 1 );

	foreach ( $time as $n => $v )
	{
		$s = ( $out[$n] = $s >= $v ? ( $n == 'years' ? floor ( $s / $v ) : sprintf ( "%02d", floor ( $s / $v ) ) ) : 0 ) > 0 ? $s % $v : $s;
	}

	return ( $out );
}

$new = tick_count ( '37262521' );

print_r($new);

?>

printf
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

what's the point of casting $time to int?
Post Reply