Watkins Web 3: Blog

Cheat Sheet: PHP Functions

Functions are a very powerful tool in PHP that help you follow the “DRY” rule of programming: Don’t Repeat Yourself. Functions essentially let you use and construct self-contained actions that can be executed multiple times throughout your page or your website. Think of a function as a little factory: you give some input, and the function “returns” some output to you. As long as you know what the function does, you don’t need to worry about its particular internal mechanics — and you won’t see the process — each time you run it.

Here are three things to remember about functions:

  1. Functions can output information into your document (if they use an echo or print statement), but more often they just return information. “Returning” the info allows it to be stored in a variable of your choosing, but it does NOT echo it. It’s mainly an issue of control: when a function returns a value, you can store itin a variable and manipulate it further before you decide to echo it.
  2. Some functions require one or more inputs (aka “parameters” or “arguments”) to work, and behave differently depending on what you input. Other functions don’t need any input. Still others make the input optional and use a default value if you don’t specify one.
  3. Some functions are native to the PHP processor, but you can also define your own. To do so, use the word function, your function name (with parentheses), and then curly braces specifying what should happen with whatever inputs are provided. See “Defining your Own Functions” below for an example.

Running Functions

PHP functions can be recognized by the syntax function_name() or function_name ("some input"); the parentheses are the place we insert our parameters, if any. The date() function, built-into PHP, uses the server clock to look up the current date and return whatever it is to the PHP process. date() accepts a letter of the alphabet so that you can choose what part of the current date — and in what format — you want the function to return a value. (It’s hard to remember which letter input retreives which output — most people just look up the answer on this PHP.net reference page).

A small number of functions can be run without storing their returned output. The classic example is echo, which takes as its input whatever string you want to appear in the web page:

	$my_message = "Hello World"
	echo ($my_message); // outputs "Hello World" on the web page.

Another example is date_default_timezone_set, which takes a location string as its argument and alters the time zone setting for subsequent PHP code:

bc(brush: php). date_default_timezone_set(‘America/Chicago’); // doesn’t echo anything, but any date or time function run after this will be according Central Time

But more common are functions designed to have their returned values stored in variables that we create:

	$this_month_ = date('F'); // stores something like "February" in $this_month
	$this_year = date('Y'); // stores something like "2012" in $this_year 

Some functions take multiple variables as their arguments. In these cases, you need to be sure to input them in the correct order. Let’s use the substr function (“sub-string”), which needs to know both what the string is and how much of it you want in order to return a sub-string. When you look up the instructions, you’ll see you can specify (1) the string, (2) the position of the first character you want, and (3) how many characters to include from that point.

	$string = "apples";
	$segment1 = substr($string, 1, 3);  // returns and stores "ppl"
	$segment2 = substr($string, 0, 5);  // returns and stores "apple"

Defining Your Own Functions

Functions are possibly easier to understand when you define your own, rather than using one of PHP built-in functions. Here are some things to keep in mind:

  1. You only need to define your function once, and it doesn’t matter where in your web page you do so: code written before or after the function definition can “call” that function and it will work. The function does need to be defined on the same page on which it is called, but you can use a PHP include: you will often see an something like include ('site-functions.php') at the top or bottom of a page, and the site-functions.php file will be used to store every function that the site might need.
  2. Functions that take parameters/arguments need to be written like math formulas, where those parameters are variables: in other words, you need to abstract as much of the logic so that the function can be given different values and always return a different result that is correct for those inputs. See the example below:
	// define the average_these_numbers function, which requires two arguments
	function average_these_numbers($number1, $number2) {
		$sum = $number1 + $number2;
		$average = $sum/2;
		return $average;

The code above creates and defines how the function will work (note the reserved word function at the beginning), so it only needs to be done once. Once defined, that function can be run repeatedly on different number pairs:

	$avg = average_these_numbers(4, 8);  // returns and stores 6
	$avg = average_these_numbers(10, 20); // returns and stores 15
	$first_number = 4;
	$second_number = 16;
	$avg = average_these_numbers($first_number, $second_number); // returns and stores 10

Note that in the last example, the inputs were first stored in scalar variables and then passed as inputs to the function. And notice that we did not have to use $number1 and $number2 as our variable names. Yes, we happened to use $number1 and $number2 within the function definition, but once defined, we can run the function by passing any two values to it, and the function will always treat the first input as $number1 and the second input as $number2. The fact that we passed in our parameters using $first_number and second_number when running the function is no problem.

Hopefully this makes some intuitive sense — it has to do with the “scope” of the variables we are using at each stage. You can read more about variable scope on the PHP.net site.