Mark’s Site

Pensieve for coding and golf :-)

All About Functions

By admin • Apr 16th, 2008 • Category: 1.2. Code Basics

Functions are simply a way of grouping code that performs some specific purpose. For example, you may have a system that relies on some random number generation algorithm. Instead of creating that random number logic every time you need it, whack it all into a function and just call that function when you need it. This serves two purposes:

  1. it unclutters your code, making things much easier to read
  2. cuts down on code in cases where you would be requiring to call that same code more than once.

This 2nd feature is more a benefit of PHP includes (you include the functions file, then call the same function whenever you want), but we can get away with giving functions some of the credit :-)

Real world example

An example function. Let’s say I needed to convert a string to uppercase and add a full stop at the end of it. I would simply create a function to do this work for me, as follows:

<?php
function convert_string($my_string){
    //convert to uppercase
    $my_string = strtoupper($my_string);
    //add full stop at end
    $my_string = $my_string . '.';
    return $my_string;
} //end function

$some_string = 'This is a test';

//run through our function to get the output we want.
echo $convert_string($some_string);

//will output: THIS IS A TEST.
?>

It’s as easy as that! If you want to give functions a try, how about modifying your ‘Hello World’ example, using something like the above. Print “HELLO WORLD!!!” to the screen after giving a function the lower case version, without the exclamations. Have fun :-)

admin is
Email this author | All posts by admin

Leave a Reply