PHP - My SQL (Chapter - 6: PHP Functions)

Math, String, Variable, Date & Time, Includes & Requires, Mail, UDF

1. PHP Math Functions


PHP provides nearly fifty functions that can perform various mathematical functions. Combined with mathematical operators, they can make your homework a lot easier!

The simplest math functions are those that only require a single parameter. This parameter is usually a number, which is accepted either as a variable or a string. The ceil() function, for example, will return a number rounded up to the nearest full number.


<?php
     $num = 55;
     echo ceil($num);
    // Result Will Be: 55

    $result = ceil(295.34);
    echo $result;
    // Result Will Be: 296
?>

As you can see, the results of these functions can be echoed, stored in a variable, etc.

Some math functions accept multiple parameters. The rand() function, for example, generates a random number in between the two numbers that it is given. Multiple parameter are separated by commas.


<?php
    echo rand(0, 500);
    // Result Is: 200
?>

If you refresh the page, you will see the above result change each time to a random number between 0 and 500.

Below is a list of almost twenty useful math functions, along with a brief description and required parameters.


Function(Para) Description
rand(min_number, max_number) Returns a Random Integer
ceil(number) Returns the Value of a Number Rounded Upwards to the Nearest Integer
floor(number) Returns the Value of a Number Rounded Downwards to the Nearest Integer
abs(number) Returns the Absolute Value of a Number
base_convert(number) Converts a Number From One Base to Another
bindec(binary_number) Converts a Binary Number to a Decimal Number
decbin(decimal_number) Converts a Decimal Number to a Binary Number
dechex(decimal_number) Converts a Decimal Number to a Hexadecimal Number
decoct(decimal_number) Converts a Decimal Number to an Octal Number
fmod(number, divisor) Returns the Remainder (Modulo) of the Division of the Arguments
hexdec(hex_number) Converts a Hexadecimal Number to a Decimal Number
is_finite(number) Returns True if a Value is a Finite Number
is_infinite(number) Returns True if a Value is an Infinite Number
is_nan(value_to_check) Returns True if a Value is Not a Number
max(number1, number2) Returns the Number With the Highest Value of Two Specified Numbers
min(number1, number2) Returns the Number With the Lowest Value of Two Specified Numbers
pi() Returns the Value of PI
pow(x, y) Returns the Value of "x" to the Power of "y"
round(number, optional) Rounds a Number to the Nearest Integer (Number of Digits After Decimal Point Optional)
sqrt(number) Returns the Square Root of a Number

A complete list of the math functions available can be found in the official PHP manual. Each function includes examples that will help you understand how to use it.

2. PHP String Functions


PHP provides nearly one hundred functions that can manipulate strings in various ways. Some (but not all!) of the functions that can be performed on strings are:

  • Compare Two Strings
  • Find a String In Another String
  • Find Out How Many Instances of A String Occur In Another String
  • Return Part of a String
  • Replace Part of a String
  • Trim Whitespace From The Ends of a String
  • Make An Entire String Lowercase or Uppercase
  • Convert All Applicable Characters In a String to HTML Entities, or Vice Versa
  • Strip HTML & PHP Tags From Inside of a String

The simplest string functions are those that only require a single parameter. This parameter is the string itself, which is accepted either as a variable or as a single or double-quoted string. The strlen() function, for example, will return the length of the string that it is given.

<?php
    $string = "What is the definition of a caterpillar?";
    echo strlen($string); // Result Will Be 40

    echo strlen("A worm in a fur coat!"); // Result Will Be 21

    $string_length = strlen($string);
    // The Length of $string (40) Is Now Stored In $string_length
?>

As you can see, the results of these functions can be echoed, stored in a variable, etc.

Most functions accept multiple parameters. The strpos() function, for example, searches for occurrences of a string inside of another string, and requires two parameters in order to function. Multiple parameter are separated by commas.

<?php
     $str = "There were four cats in a boat, one jumped out. How many were left?";
     echo strpos($str, "cat"); // Result Will Be 16
?>

The strpos() function will return a number indicating the position of the first match that it encounters. If you begin to do the counting yourself, you will see that the "c" for "cat" is the 17th character... so why did the function say 16? This is because most PHP functions begin counting with 0, so the position of the string's first character is 0, the second character is 1, etc.

(By the way, there were no cats left in the boat, because they were all copy cats.)

Below is a list of fifty useful string functions, along with a brief description and required parameters.


Function(Parameters) Description
echo(string) Outputs Strings
print(string) Outputs a String
printf(string) Outputs a Formatted String
ltrim(string) Strips Whitespace From the Left Side of a String
rtrim(string) Strips Whitespace From the Right Side of a String
trim(string) Strips Whitespace From Both Sides of a String
lcfirst(string) Makes a String's First Character Lowercase
ucfirst(string) Makes a String's First Character Uppercase
strtolower(string) Converts a String to Lowercase Letters
strtoupper(string) Converts a String to Uppercase Letters
str_word_count(string) Count the Number of Words In a String
ucwords(string) Makes the First Character of Each Word In a String Uppercase
wordwrap(string, width, break) Wraps a String to a Given Number of Characters (Default Width: 75) (Default Break: \n)
count_chars(string) Returns How Many Times an ASCII Character Occurs Within a String & Returns the Information
substr_count(string, substring) Counts the Number of Times a Substring Occurs In a String
str_pad(string, length, pad_string) Pads a String to a New Length
strlen(string) Returns the Length of a String
substr(string, start) Returns a Part of a String (Start Value of "0" to Begin at First Character)
strrev(string) Reverses a String
str_shuffle(string) Randomly Shuffles All Characters In a String
str_repeat(string, repeat) Repeats a String a Specified Number of Times ("Repeat" Is Number of Times to Repeat)
strpbrk(string, characters) Searches a String For Any of a Set of Characters
str_replace(find, replace, string) Replaces Some Characters In a String (Case-Sensitive)
substr_replace(string, replacement, start) Replaces a Part of a String With Another String
stristr(string, search) Finds the First Occurrence of a String Inside Another String (Case-Insensitive)
strstr(string, search) Finds the First Occurrence of a String Inside Another String (Case-Sensitive)
strrchr(string, char) Finds the Last Occurrence of a String Inside Another String
stripos(string, find) Returns the Position of the First Occurrence of a String Inside Another String (Case-Insensitive)
strpos(string, find) Returns the Position of the First Occurrence of a String Inside Another String (Case-Sensitive)
strripos(string, find) Returns the Position of the Last Occurrence of a String Inside Another String (Case-Insensitive)
strrpos(string, find) Returns the Position of the Last Occurrence of a String Inside Another String (Case-Sensitive)
strcasecmp(string1, string2) Compares Two Strings (Case-Insensitive)
strcmp(string1, string2) Compares Two Strings (Case-Sensitive)
strtok(string, split) Splits a String Into Smaller Strings
chunk_split(string, length) Splits a String Into a Series of Smaller Parts (Default Length Is 76)
str_split(string, length) Splits a String Into an Array
explode(separator, string) Breaks a String Into an Array
implode(separator, array) Returns a String From the Elements of an Array
str_getcsv(string, delimiter, enclosure) Parses a CSV String Into an Array
addcslashes(string) Returns a String With Backslashes In Front of Single Quotes, Double Quotes & Backslashes
stripcslashes(string) Unquotes a String Quoted With addcslashes()
addslashes(string,characters) Returns a String With Backslashes in Front of Predefined Characters
stripslashes(string) Unquotes a String Quoted With addslashes()
nl2br(string) Inserts HTML Line Breaks In Front of Each Newline In a String
strip_tags(string) Strips HTML & PHP Tags From a String
html_entity_decode(string) Converts HTML Entities to Characters
htmlentities(string) Converts Characters to HTML Entities
htmlspecialchars_decode(string) Converts Some Predefined HTML Entities to Characters
htmlspecialchars(string) Converts Some Predefined Characters to HTML Entities
get_html_translation_table() Returns the Translation Table Used by htmlspecialchars() & htmlentities()

A complete list of the string functions available can be found in the official PHP manual. Each function includes examples that will help you understand how to use it.

3. PHP Variable Functions


PHP provides over thirty functions that can perform various functions related to variables. Most are beyond the scope of this tutorial, but several are useful, and even necessary to know.

Before we learn about the functions, let's take a look at the different types of data that can be stored in variables. Although PHP automatically assigns the data type of each variable based on the data that it contains, it will be good to know a little about each one.


TypeDescription
StringSequences of Characters, Such As This Statement
IntegerWhole Number, Positive or Negative, Without a Decimal Point
FloatFloating Numbers, With a Decimal Point
BooleanHas Only Two Possible Values: "TRUE" or "FALSE"
ArrayNamed/Indexed Collection of Other Values
ObjectProgrammer-Defined Classes
ResourceHold References to External Resources (Database Connections, Etc.)
NULLHas Only One Possible Value: NULL

Got all that? I didn't either when it was first introduced to me, and I've never really needed it, so let's move on.

Probably the most commonly used variable function is the isset() function, and, as the name implies, it can tell you whether or not a variable has been set.


<?php
     $question = "What's the unluckiest kind of cat to have?
";
    if (isset($question)) {
        echo $question;
        echo "A catastrophe!";
    } else {
         echo "If you don't have a question you don't get an answer.";
    }
?>

The empty() function will determine whether or not a variable contains actual data. An empty string "", 0, NULL & FALSE are all considered empty variables.


<?php
     $question = "What do you get when two giraffes collide?<br>";
    if (!empty($question)) {
        echo $question;
        echo "A giraffic jam.";
        unset($question);
    } else {
        echo "If you don't have a question you don't get an answer.";
    }
?>

The unset() function, confusingly stuck in the example above, will unset the variable so that it is not longer set. It can be reset later in the script, but until then it no longer exists.

Below are these and a few other variable functions that can be useful.

Function Description
isset() Determines If a Variable Is Set and Is Not NULL
empty() Determines Whether a Variable Is Empty
gettype() Gets the Type of a Variable
settype() Sets the Type of a Variable
unset() Unsets a Given Variable

A complete list of the variable functions available can be found in the official PHP manual. Each function includes examples that will help you understand how to use it.

4. PHP Date & Time Functions


There are nearly fifty date and time functions, so for the purpose of this tutorial we will narrow them down to three.


Function Description
time() Returns the Current Time as a Unix Timestamp
date() Formats a Local Time/Date
strtotime() Parses an English Textual Date or Time Into a Unix Timestamp

Since we will be using the word "timestamp" throughout this page, we will begin by explaining what it is. A Unix Timestamp is the number of seconds that have passed since January 1, 1970. Currently, the timestamp is 1405345249, but since it changes every second, the number will increase if you refresh the page. (The timestamp reflects the time set on the server, and not on the client's computer.)


The PHP Time() Function


The time() function returns the current timestamp. The timestamp that you see in the previous paragraph is generated by a very small line of code: <?php echo time(); ?>

The time() function can also return a modified timestamp. You can add or subtract any number of seconds to the function in order to return the timestamp of a previous or upcoming date and time.

For example, to return a timestamp for next week, or to return a timestamp from last week, I can add or subtract 7 days by determining how many seconds are involved (7 days * 24 hours per day * 60 minutes in an hour * 60 seconds in an hour = number of second in 7 days).


<?php
     $last_week = time() - (7 * 24 * 60 * 60);
    $next_week = time() + (7 * 24 * 60 * 60);
    $next_month = time() + (30 * 24 * 60 * 60);
    echo "Last Week: " . $last_week . "<br />";
    echo "Next Week: " . $next_week . "<br />";
    echo "Next Month: " . $next_month . "<br />";
?>

The result will be:


Last Week: 1404740449
Next Week: 1405950049
Next Month: 1407937249

The PHP Strtotime() Function


The strtotime() function accepts an English datetime description and turns it into a timestamp. It is a simple way to determine "next week" or "last monday" without using the time() function and a bunch of math.

Some examples are:


<?php
     echo strtotime("now") . "<br />";
     echo strtotime("tomorrow") . "<br />";
    echo strtotime("yesterday") . "<br />";
    echo strtotime("10 September 2000") . "<br />";
    echo strtotime("+1 day") . "<br />";
    echo strtotime("+1 week") . "<br />";
    echo strtotime("+1 week 2 days 4 hours 2 seconds") . "<br />";
    echo strtotime("next Thursday") . "<br />";
    echo strtotime("last Monday") . "<br />";
    echo strtotime("4pm + 2 Hours") . "<br />";
    echo strtotime("now + 2 fortnights") . "<br />";
    echo strtotime("last Monday") . "<br />";
    echo strtotime("2pm yesterday") . "<br />";
    echo strtotime("7am 12 days ago") . "<br />";
?>

The PHP Date() Function


The date() function formats a timestamp so that it actually makes sense, such as 6:40 AM Monday, July 14, 2014.

The date() function accepts two arguments, according to the following syntax: date(format, timestamp);. The first argument is the format that you want the timestamp in. The second argument (optional) is the timestamp that you want formatted. If no timestamp is supplied, the current timestamp will be used.

PHP provides over thirty-five case-sensitive characters that are used to format the date and time. These characters are:


  Character Description Example
Day j Day of the Month, No Leading Zeros 1 - 31
Day d Day of the Month, 2 Digits, Leading Zeros 01 - 31
Day D Day of the Week, First 3 Letters Mon - Sun
Day l (lowercase 'L') Day of the Week Sunday - Saturday
Day N Numeric Day of the Week 1 (Monday) - 7 (Sunday)
Day w Numeric Day of the Week 0 (Sunday) - 6 (Saturday)
Day S English Suffix For Day of the Month st, nd, rd or th
Day z Day of the Year 0 - 365
Week W Numeric Week of the Year (Weeks Start on Mon.) 1 - 52
Month M Textual Representation of a Month, Three Letters Jan - Dec
Month F Full Textual Representation of a Month January - December
Month m Numeric Month, With Leading Zeros 01 - 12
Month n Numeric Month, Without Leading Zeros 1 - 12
Month t Number of Days in the Given Month 28 - 31
Year L Whether It's a Leap Year Leap Year: 1, Otherwise: 0
Year Y Numeric Representation of a Year, 4 Digits 1999, 2003, etc.
Year y 2 Digit Representation of a Year 99, 03, etc.
Time a Lowercase Ante Meridiem & Post Meridiem am or pm
Time A Uppercase Ante Meridiem & Post Meridiem AM or PM
Time B Swatch Internet Time 000 - 999
Time g 12-Hour Format Without Leading Zeros 1 - 12
Time G 24-Hour Format Without Leading Zeros 0 - 23
Time h 12-Hour Format With Leading Zeros 01 - 12
Time H 24-Hour Format With Leading Zeros 00 - 23
Time i Minutes With Leading Zeros 00 - 59
Time s Seconds With Leading Zeros 00 - 59
Timezone e Timezone Identifier Example: UTC, Atlantic
Timezone I (capital i) Whether Date Is In Daylight Saving Time 1 if DST, otherwise 0
Timezone O Difference to Greenwich Time In Hours Example: +0200
Timezone P Difference to Greenwich Time, With Colon Example: +02:00
Timezone T Timezone Abbreviation Examples: EST, MDT ...
Timezone Z Timezone Offset In Seconds -43200 through 50400

Using a combination of these characters and commas, periods, dashes, semicolons and backslashes, you can now format dates and times.


<?php
// Will Echo: 6:40 AM Monday, July 14, 2014
echo date("g:i A l, F d, Y");

// Will Echo: 2014-07-13
$yesterday = strtotime("yesterday");
echo date("Y-m-d", $yesterday);
?>

Calculating Past & Future Dates


It is very simple to compare two dates in php, to verify if one is past, present or future. Since all dates can be converted back into timestamps, all it takes is a simple comparison of the two timestamps, which are essentially numbers. If the date in question is a bigger number than the current date, than you know that your date is in the future, and if the date is smaller than the current date, you know that the date is already past.


<?php
     $my_date = strtotime("10 April 2005");
     if(strtotime($my_date) > time()) {
        echo "Future Date!";
    } if(strtotime($my_date) < time()) {
        echo "Past Date!";
    } if(strtotime($my_date) == time()) {
        echo "Current Date!";
    }
?>

5. PHP Includes & Requires


The include() function allows you to insert one file's contents into another file when that other file is executed.

In English, this means that if you want something like a header, footer, navigation, block of PHP code, etc. to appear on multiple pages of your website, there is a solution that does not involve typing it in every time. By putting this information into separate files and including those files whenever necessary, you can save on time, space and clutter by updating only a single file.

This function includes files with extensions such as .inc, .html, .php & .txt as needed. It includes data such as HTML markup, PHP code, and/or text. The best part is that if the included file contains PHP code, that PHP code can be used in (referenced by) the file that is doing the including.

(Example: If $variable is set in page1.php and page1.php is included in page2.php, then $variable can be used in page2.php below where the include() function includes page1.php.)

The include() function syntax is: include("path to file + name of file + file extension");


<?php
    include("http://www.binitpatel.co.in/somefile.php");
?>

If the file cannot be found, or cannot be opened, etc. an error will be spit out on the page, and the remainder of the page will be executed normally.

The require() function is identical to the include() function, with the exception that, if the file cannot be found or the page cannot be opened, the require() function considers the error to be fatal and stops executing the remainder of the file. For this reason, require() is recommended instead of include(), because scripts should not continue after an error.

The include_once() and require_once() functions perform exactly the same as include() and require(), with the exception that, as their name implies, if the code from their files has already been included in the file, they will not be included again.

Guess what? You can name your included files anything you want, because your visitors will never see your included files, or even know that they exist!

I should probably mention that the include() and require() "functions" are not really functions, and that they are "language constructs" like the echo "function", but who cares, right?!

6. PHP Mail Function


The mail() function allows you to send emails, as long as the server has a fully-functional email system already set up.

This function accepts five different parameters, only four of which we will discuss here, and only three of which are required.


Parameter Importance Description
to Required Recipient(s) of Email
subject Required Subject of Email
message Required Message Body of Email
headers Optional From, Reply-To, CC, BCC, Date, Etc.

Listed in order of appearance, the parameters are: mail(to,subject,message,headers)

One of the most simple examples of the mail() function is:


<?php
    mail("an-email@a-domain.com","Brilliant Subject","Boring message body.");
?>

The addition of headers allows you to specify who the email is from and who should be copied and/or blind copied on an email


<?php
     $to = "an-email@a-domain.com";
    $subject = "Why do dogs bury bones in the ground?";
    $message = "Because they can't bury them in trees!";
    $headers = 'From: ' . "\r\n";
    $headers .= 'Reply-To: an-email@a-domain.com' . "\r\n";
    $headers .= 'Cc: an-email@a-domain.com' . "\r\n";
    $headers .= 'Bcc: an-email@a-domain.com' . "\r\n";
    mail($to,$subject,$message,$headers);
?>

HTML emails can be sent by specifying the appropriate content-type in the header.


<?php
     $to = "an-email@a-domain.com";
    $subject = "This is an HTML email!";
    $message = "
    <html>
    <body>
    <h2>Cool, right?</h2>
    </body>
    </html>
    ";     $headers = 'From: ' . "\r\n";
    $headers .= "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
    mail($to,$subject,$message,$headers);
?>

7. PHP Regular Expressions


Regular expressions are patterns that define a list of characters. They can be used to search, replace and otherwise work with strings, but are most commonly used to validate forms, since forms allow users to enter in unknown data. We will learn here how to determine whether or not an email address uses the correct syntax.

In the past, PHP supported two methods of pattern matching (POSIX and PCRE). Now, PHP is dropping support for POSIX methods, leaving PCRE (Perl-Compatible Regular Expressions) our subject matter for this tutorial.

Regular expressions have their own set of functions:


Function Description
preg_filter() Performs a Regular Expression Search & Replace
preg_grep() Returns Array Entries That Match the Pattern
preg_last_error() Returns the Error Code of the Last PCRE Regex Execution
preg_match_all() Performs a Global Regular Expression Match
preg_match() Performs a Regular Expression Match
preg_quote() Quote Regular Expression Characters
preg_replace_callback() Performs a Regular Expression Search & Replace Using a Callback
preg_replace() Performs a Regular Expression Search & Replace
preg_split() Splits a String By a Regular Expression

There are two types of regular expressions. "Literal" characters are those that match themselves, and "metacharacters" are those that have another meaning. "Literal" characters can be a single character, a word, a phrase, etc. that is taken literally, at face-value. Using the preg_match() function, let's look at an example of a literal regular expression. (Note: Literal and metacharacter patterns must both be enclosed in slash "/" delimiters, as seen in our example below.)


<?php
    $string = "Which side of a chicken has the most feathers?";
    if (preg_match("/chicken/", $string)) {
        echo $string . "<br>";
        echo "The outside.";
    }
?>

Since in our example a match is found, the question and answer will be echoed. If you change the word "chicken" in either one of the instances where it is found, there will no longer be a match, and the statements will not be echoed.

Metacharacters are understandably more involved than their literal counterparts, but with a little study, they can be interpreted. Let's begin with an easy subject: character classes.

Character classes specify which characters are acceptable in a pattern. [a-z], [A-B] and [0-9] are all examples of character classes covering a wide range of characters, but you can build your own by enclosing the acceptable characters in square brackets. Examples: [dgefgh] matches d, g, e, f, etc. and [l-p] matches l, m, n, o & p.

Negated character classes specify which characters are not acceptable in a pattern. These classes are in square brackets, but begin with ^. Examples: [^dgefgh] means that d, g, e, f, g & h are not acceptable and [^l-p] means that l, m, n, o & p are not acceptable.

And now let's take a brief look at the basic possibilities that regular expressions allow.


Syntax Example Will Match Description
a-z [a-z] a, b, c, d, etc. Represents All & Any Number of Lowercase Alphabet Characters
A-Z [A-Z] A, B, C, etc. Represents All & Any Number of Uppercase Alphabet Characters
0-9 [0-9] 0, 1, 2, etc. Represents All & Any Number of Numeric Characters
a-zA-Z0-9 [a-zA-Z0-9] a, B, 7, etc. Represents All & Any Number of Alphanumeric Characters
^ ^cat cat Indicates That Pattern Must Match Beginning of String
$ cat$ cat Indicates That Pattern Must Match End of String
^$ ^cat$ Indicates That Pattern Must Match Beginning & End of String
| cat|dog Indicates An Alternative Pattern (Means "Or")
. c.t cat, cot, cut, c8t etc. Represents Any Single Character Except Newline
\i \icat cat, CAT, cAt, CAt, etc. Represents Case Insensitivity
\b \bcat cat (not cattail, cats, etc.) Represents "Word Boundary" (No Additional Characters)
\d c\dt c0t, c1t, c2t, c3t, c4t, c5t etc. Represents Any Single Digit (0-9)
\D c\Dt cat, cot, cut, etc. Represents Any Single Character Except Digit (a-z)
\w c\wt cat, c9t, c_t, etc. Represents Any Letter, Digit & Underscore
\W c\Wt c$t, c@t, c&t, etc. Represents Any Character Except Word Characters
\s c\st c t Represents Any Whitespace Such As a Space, Newline or Tab
\S c\St cat, c9t, c_t, etc. Represents Any Character Except a Whitespace Character
\ c\.t c.t Escapes Special Characters So They Can Be Used In Pattern to Represent Themselves
() (cat) Used to Group Options Together By Capturing Subpatterns
[] [abcde] Used to Group Options Together By Forming Classes
+ cat+ Means That There Should Be One or More Occurrence of the Preceding Character or Expression
* cat* Means That There Should Be Zero or More Occurrence of the Preceding Character or Expression
? cat? Means That There Should Be Zero or One Occurrence of the Preceding Character or Expression
{} cat{2} Means That There Should Be A Certain Number (2) of Occurrences of the Preceding Character or Expression
{} cat{5,7} Means That There Should Be A Certain Number (Between 5 & 7) of Occurrences of the Preceding Character or Expression

Now that you have all of that memorized, let's jump into our long-awaited example, where we will determine whether or not an email address uses the correct syntax. Consider the following by looking up each symbol on the chart above, and see what you make of it.

/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/

As you can see, this regular expression defines a series of rules that express an acceptable pattern to be followed in order to validate the proper syntax of an email address. It can be used in the following manner:


<?php
     $email = "test@example.org";
     $expression = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
    if (preg_match($expression, $email)) {
        echo "Email format is correct!";
    } else {
        echo "Email format is NOT correct!";
    }
?>

Try playing around with the email address to see what formats are allowing with the regex pattern used, the make up some patterns of your own, the possibilities are endless... well, almost.

8. User-Defined PHP Functions


We have been learning about all kinds of useful functions that come built-in with PHP, but what if you can't find a function to perform a certain task? What if it does not exist? PHP allows you to build your own functions.

Why build a function? Why not just write the code needed to perform the task and move on? If you think you might use a block of code more than once, it will save a lot of time and effort to put it in a function and call the function as many times as necessary later on in the page. You can even store your function(s) in a separate file and include the file on as many pages as needed.

To create a function, the syntax is: function name() { }

You can name a function anything you want, as long as the function name is not already in use as a PHP function. Function names are not case sensitive, and can include letters, numbers and/or underscores, but can only begin with letters or underscores. Let's take a look at a simple function:


<?php
     function test() {
         echo "I am in a function!";
     }
?>

So what does this function do? Nothing! Why? Because it has not yet been called. Until a function is called, it will sit around looking bored (or boring), waiting to be of use... Let's learn how to call our poor function and give it something to do:


<?php
    function test() {
         echo "I am in a function!";
    }

    test();
?>

Simple! Too simple? Probably. All that the function does now that it is called is echo a single statement. Let's try something a bit more complex.


<?php
     function mathy_stuff($a, $b) {
        echo $a * $b;
    }

    mathy_stuff(5, 7);
    mathy_stuff(3, 100);
    mathy_stuff(7000, 68);
?>

Now, when our new function is defined, we have two parameters, or variables, between the function's parentheses. These variables are used in the function, where they are multiplied by one another and echoed. The variables are not actually assigned their values until the function is called, at which point the values are listed in the function's parentheses, comma-separated in the order of the variables they need to be assigned to. A function can handle as many (or few) comma-separated parameters as you (the programmer) can keep track of, if necessary.

Returning values allows you to store the results of a user-defined function in a variable. Consider the following:


<?php
     function example($a, $b) {
        $total = $a + $b;
        return $total;
    }

    $addition = example(50, 51);
    echo $addition . " dalmations!";
?>

As you can see, instead of echoing the result of $a + $b, we store it in a variable and then return that variable. (A function can only return one thing, so choose carefully!) Then, the function is called as the value of the $addition variable, and is assigned two values to use in the function. At last, the $addition variable (containing the results of the function) is echoed along with a short string of text.

Some people consider functions hard to get a handle on, but it is not really much harder than learning how to ride a bike, and it is a lot easier on the knees!

Continue to Index

Welcome to HoneyBee - The Learning Platform

By Binit Patel

HoneyBee is a learning platform which is an integrated set of informative online services that enable learners involved in education with information, tools and resources to support and enhance Teaching, Learning and Management.

Contact With Me