So Much C# for a PHP Guy

Blog

I noticed that most of my posts and projects have been quite centered around C# and application development instead of PHP and web development. To tell you the truth, I’m a little afraid of releasing my PHP code. Trust me, I write in true PHP 5 – very class oriented, none of this HTML intertwined between PHP code bull. It’s more that I want the code to be perfect before I release it. Starting now, I’ll try to share some useful functions I wrote that might help you on your quest to developing a PHP website.

Today, I’ll show you a quick function that converts time in words to seconds. Well, let’s say you are using memcached and you want to save an item for X seconds.  It may be simple to put 60 for a minute or 3600 for a hour, but larger than that gets complex and not so easy to reverse (129600 is a day and a half).  This function converts simple terms like “1d 6h” or “2h 24m 15s” to their seconds counterpart.

For the record, w = week, d = day, h = hour, m = minute, s = second.

  1. /**
  2.  * This will convert from text like "2m 5s" to 125 seconds.
  3.  */
  4. function ttos($timeString) {
  5.   $seconds = 0;
  6.  
  7.   $timeArray = explode(" ", $timeString);
  8.   $timeLength = count($timeArray);
  9.  
  10.   for ($x = 0; $x < $timeLength; $x++) {
  11.     $type = substr($timeArray[$x], -1);
  12.     $value = substr($timeArray[$x], 0, -1);
  13.  
  14.     if (is_numeric($value)) {
  15.       switch ($type) {
  16.         case "s":
  17.           $seconds += $value;
  18.           break;
  19.         case "m":
  20.           $seconds += $value * 60;
  21.           break;
  22.         case "h":
  23.           $seconds += $value * 3600;
  24.           break;
  25.         case "d":
  26.           $seconds += $value * 86400;
  27.           break;
  28.         case "w":
  29.           $seconds += $value * 630000;
  30.           break;
  31.       }
  32.     }
  33.   }
  34.  
  35.   return $seconds;
  36. }

If you think this function could be better, please drop me a comment. I’m always willing to improve! :D

No Comments

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



  • Donate

    If my work has helped you and you want to return the favor, you could purchase something for me from my Amazon Wish List or send me a donation via PayPal.

  • My Lifestream

  • License

    Unless otherwise noted, all source code and compiled files published on this website are released under the terms of the GNU Lesser General Public License.