Reusable PHP Functions

When we start a new custom programming project we typically begin by copying and pasting a handful of useful functions that we have developed for previous projects. Most developers will put together a toolbox like this -- if you haven't, you can save yourself a lot of hassle by doing so. The first step is to make sure that you're wrapping any potentially reusable code in a function. For example:

// Proper formatting for print_r
// $array = array to display
function print_array($array) {
  print '<pre>';
  print_r($array);
  print '</pre>';
}

Simple and useful, this function allows for easy viewing of arrays. The default print_r function does its job but does so in a fairly hard-to-read format. This one just wraps that function in <pre> tags to preserve the formatting. Here's another:

// Trim function - cuts text to a certain length
// $string = string to trim; $max_length = longest allowed string before trimming; $append = characters to add on after the trim (typically "...")
function neat_trim($string, $max_length, $append = '')
{
  if (strlen($string) > $max_length) {
    $string = substr($string, 0, $max_length);
    $pos = strrpos($string, ' ');
    if ($pos === false) {
      return substr($string, 0, $max_length) . $append;
    }
    return substr($string, 0, $pos) . $append;
  }
  else {
    return $string;
  }
}

This one accepts a string of text and chops it to a specified length and tacks on the value of $append (usually something like "...") at the end. You can create all sorts of small functions like this to simplify formatting of dates, checking length of field or integer values, or other form validation requirements.

We also set up several validation functions which can be used in forms to make sure the end users are entering the proper information. Here are a few examples:

// Confirm valid integer
function int_check($string) {
	$pattern = "/^([0-9])+$/";
  if (preg_match($pattern,$string)) {
		return true;
  }
  else {
   return false;
  }
}
// Confirm valid numeric
function numeric_check($string) {
	$regex = '/^\s*[+\-]?(?:\d+(?:\.\d*)?|\.\d+)\s*$/';
  return preg_match($regex, $string); 
}

You will likely find yourself working with arrays in various formats. We created a few array functions to handle various tasks such as splitting a string into a multidimensional array (and converting back again), and making sure that an array contains unique items. Here's how we handled these needs:

// Explode a string into a multi-dimensional array
// $delimiters = array of delimiters to use, $string = string to be split
function multiexplode($delimiters, $string) {
	$singlearray = explode($delimiters['0'], $string);
	foreach ($singlearray as $arrayitem) {
		$multiarray[] = explode($delimiters['1'], $arrayitem);
	}
	return $multiarray;
}
// Converts a two dimensional array to a simple one
// $array = the array to work with
function multitosimple($array) {
	$newarray = array();
	foreach ($array as $item) {
		$newarray[$item[0]] = $item[1];
	}
	return $newarray;
}
// Checks for unique values in an array
// $array = array to check
function check_unique_array($array) {
  return array_unique($array) == $array;
}

Hopefully a few of these functions have helped. Either way, it's always a good idea to work up a few useful reusable functions that can be moved from project to project to save you time. No sense reinventing the wheel each time!

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Questions?

Do you have a question about something you saw here in our blog? Are you interested in a custom website for your business? If so, please contact us here.