Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Gabe da Silveira http://www.darwinweb.net/

« Newer Snippets
Older Snippets »
2 total  XML / RSS feed 

Calculate Thanksgiving Date

This is the most concise way I've seen to calculate Thanksgiving date (in PHP).

strtotime("3 weeks thursday",mktime(0,0,0,11,1,$year)

Selecting and checking items from HTML menus

This code allows you to pass in an HTML menu (select, radio, or checkbox) along with a single choice or an array of choices to be selected. The choice(s) should be contained literally in the value attribute.

This is handy for making persistent forms without polluting the HTML with PHP logic. For example, you could initialize all your menus to have nothing selected and then pass in GET or POST variables in case the form was not accepted, easily making form selections persistent.

/**
 * For select menus.
 */
function select_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ selected(="selected")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 selected=\"selected\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 selected=\"selected\"",$menu);
  }
  
  return $menu;
}

/**
 * For radio buttons and checkboxes.
 */
function check_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ checked(="checked")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 checked=\"checked\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 checked=\"checked\"",$menu);
  }

  return $menu;
}
« Newer Snippets
Older Snippets »
2 total  XML / RSS feed