Clean code

Writing cleaner conditional statements

Just a thought on using cleaner code while using a lot of nested if statements.

Clean code

Clean code

Ugly code

if(process_x()) {
    /* do a lot of other things */
    if(process_y()) {

         /* do a lot of other things */
         if(process_z()) {
              /* do a lot of other things */
              /* SUCCESS */
         }
         else {
              clean_all_processes();
         }
    }
    else {
         clean_all_processes();
    }
}
else {
    clean_all_processes();
}

Good looking code

do {

  if( !process_x() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_y() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_z() )
    { clean_all_processes();  break; }

  /* do a lot of other things */
  /* SUCCESS */

} while (0);

The use of goto is an alternative, the bad thing about this is you always need to define the label.

TimeAgo function in PHP

This can be used for comments and other from of communication to tell the time ago instead of the exact time which might not be correct to some one in another time zone.

The function only uses unix time stamp like the result of time();

function timeago($time) {
        $time = strtotime($time);
        $periods = array(L('second'), L('minute'), L('hour'), L('day'), L('week'), L('month'), L('year'), L('decade'));
        $periodsPlural = array(L('seconds'), L('minutes'), L('hours'), L('days'), L('weeks'), L('months'), L('years'), L('decades'));
        $lengths = array("60","60","24","7","4.35","12","10");

        $now = time();

        $difference     = $now - $time;
        $tense         = L('ago');

        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)
        {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        if($difference != 1)
        {
            return "$difference $periodsPlural[$j] $tense";
        } else {
            return "$difference $periods[$j] $tense";
        }
    }

Needs a time() value, and it will tell you how many seconds/minutes/hours/days/years/decades ago.