Functions - LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

Chapter 5. Functions

Introduction

Functions in PHP, like in many other languages, give you the power to create extremely versatile and reusable code. Imagine the following situations. You are writing a script and you want to perform a certain set of actions. Later on, you need to perform the same set of actions, but you have to change a variable to another variable, for example. Wouldn’t it be convenient to be able to separate those actions out, and just replace the variable as needed? This is where functions come in.

In PHP, functions are broken up into user defined functions and pre-defined functions. User defined functions are custom functions that you create inside of your code. Pre-defined functions are the functions that PHP comes with.

User Defined Functions

A function is basically a block of statements that can be used repeatedly in a program that will only be executed when you call it. Functions can take parameters that you predefine or they can have no parameters. Let’s look at the syntax for a function in PHP.

The function name is defined by you. It is a good idea to give the function a name that reflects what the function will do. The naming convention for functions is pretty much the same as the naming convention for variables (functions can start with letters or underscores but not numbers). An important thing to note is that function names are not case-sensitive. Therefore, the following code will produce an error:

If you want to call the function you created, you just write the name of the function followed by a pair of parentheses. If your function takes parameters, you put the corresponding variable or variables in between the parentheses.

Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. Let’s modify the previous example to include a name:

Functions arguments can take default values. For example, if you call the function without specifying an argument, the function will assume the default argument value;

Return values

Often times, you want the function to return a specific value. To do this, you use the return statement:

Variable Scope

When dealing with variables, it is important to know what their scope is (or the context in which they are defined). For example:

In this case, the variable$var can be used by any code that is included inside offunctions.php. The context of a variable, however, changes when we create our own functions.

Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

Let’s look at how to declare variables as global.

Pre-defined functions

PHP comes built with many pre-defined functions and this is what makes PHP so efficient and useful. We cannot possible examine all of the PHP functions as this will take another book itself (currently, the PHP documentation lists 9457 built in functions.). Let’s start with the most basic functions that can be used inside of PHP.

Echo, Print, exit, die

Echo

Echo is the language construct in PHP that allows us to output string data. PHP will automatically convert numerical variables to strings. We’ve already used echo in previous examples in this book, so you should be familiar with this function by now.

Print

Print is another language construct that does the same thing as echo, but it is older and a bit slower. Therefore, it is usually better to use echo.

A function that is not exactly related to print but shares enough of the name for us to place it here, is theprint_r() function. This function allows us to print the contents of an array to the screen.

Exit and Die

These functions allow you to print out a message to the screen and terminate the script. The two functions are equivalent to one another and you can use whichever. The syntax for both is:

String functions

PHP comes with a wide range of functions for string manipulation.

Word count

PHP comes with a pre-built function that will count the number of words in a string for you. It is of the following form:

The second argument of the function is optional and can take 3 values. Here are the supported values and the result returned from each:

· 0 - returns the number of words found

· 1 - returns an array containing all the words found inside the string

· 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

The function takes a third optional argument that we didn’t specify here. The third parameter is a list of additional characters that you want to be considered as words. You just put the symbols next to each other in a string with no other formatting.

String Shuffle

This function allows you to randomly shuffle the characters inside of a string. This comes in handy if you want to create pseudo-unique names for files or something like that.

Replace parts of a string

PHP has a number of different functions that can help you with this. The simplest one is thestr_replace() function. It takes the form:

The arguments can be strings or arrays. If needle and replacement are arrays, then str_replace() takes a value from each array and uses them to search and replace on haystack. If replacement has fewer values than needle, then an empty string is used for the rest of replacement values. If needle is an array and replacement is a string, then this replacement string is used for every value of haystack. The converse would not make sense, though.

There is an optional fourth argument that could be passed which will be set to the number of replacements performed.

There is a modification to thestr_replacefunction that will replace without regard to case. In other words, it will do a case-insensitive replace. This function is calledstr_ireplace and takes the same arguments.

String length

There are a number of functions in PHP that will return the length of a string. The simplest to use is the following:

Another function you can utilize to do this is themb_strlen();

This function has an optional parameter which is the encoding of the string. For example, if you want to set the encoding to UTF-8, you just provide the string‘UTF-8’. PHP supports numerous encoding types which you can easily find by going to the official PHP manual.

Another way to count the number of characters is to use theiconv_strlen() function.It works very much like themb_strlen() function and takes the same parameters, except it is a lot stricter when it comes to bad sequences inside your string.

The reason for the different functions is that they actually count different things.strlen() counts the number of bytes inside of a string. Usually a character is equivalent to one byte, but that is not always the case. This is why the other functions exist.

Sometimes you will find that you have a string that has unneeded whitespace at the end of it.To get of whitespace on both sides of a string, you can use thetrim() function.A useful feature of thetrim() function is that it can trim not only whitespace but any additional characters that you specify.Alternatively, if you only want to trim from the left or the right, there are theltrim()andrtrim() functions.

Finding substrings in a string

The simplest way to return a part of a string is to use thesubstr() function. This function takes two required parameters and one optional parameter. The first parameter is the string that you are referencing. The second parameter is the start of the portion of the string. This parameter can be either positive or negative. If positive, the returned string will be the string that starts from the specified location within the main string. If negative, the returned string will start from the end of the main string. The third parameter is optional and is the length of the string you want returned. It can also be positive or negative. If it is positive, the returned string will contain at most, that number of characters. If the value is negative, the value specifies how many characters will be omitted from the main string. Here are examples:

If you want to find the number of times a string occurs inside another string you can use thesubstr_count() function. This function takes two required parameters and two optional parameters. Here is the syntax for the function and some examples on how to use it in your own code:

The first parameter is the string to check. The second parameter is the string to search for. The third parameter specifies where in the string to start searching. The third parameter specifies the length of the search.

Another function that finds a substring inside a larger string is thestrpos() function. This function finds the position of the first occurrence of a string inside another string. Let’s look at the syntax for the function as well as a couple of different examples to understand it:

The first parameter is the string to check. The second parameter is the string to search for. The third parameter specifies where in the string to start searching.

There is an alternative version to this function that is case-insensitive. This function is thestripos()function. It takes the same parameters as thestrpos() function and works the same way except it is case-insensitive.

There are two similar functions that will return the last occurrence of a string inside another string. Again, there is a case-sensitive and a case-insensitive version of these functions.These are thestrripos()and thestrrpos() functions. They take the same parameters as the above two functions and work in the same way.

String case switches

Sometimes you will find yourself having to convert strings from all caps to lowercase or vice versa or even have to capitalize words. Luckily, there are functions in PHP that will save you from having to do that by yourself.

The two most common and reciprocal functions arestrtolower()andstrtoupper(). Both of these functions take only 1 parameter and that is the string that you want to edit. Here is an example of both functions:

The other case functions that you might find useful aretheucwords()and theucfirst(). Here is an example:

Strings to Arrays and back

There are two very important functions in PHP that allow you to convert a string into an array and an array into a string. We’ll take a look at both.

The first function is theimplode() function. This function takes an array and joins the array elements with a string. The syntax is the following:

The separator specifies what to be placed in between the array elements. Here is an example:

This is a very powerful function that, if used properly, can save you from having to write out code and cut down on execution time. Make sure to look at the exercises at the end of the chapter to see an example of how this function can be used to optimized code performance.

Let’s look at the other function. We saw how to implode an array into a string, now let’s look at how to explode a string into an array. The function is calledexplode() and takes two parameters.

The separator is the part of the string that you want to separate by and the string is the string you are exploding. Here is an example:

Conclusion

We’ve expanded our PHP knowledge even more in this chapter by covering the topics of functions in PHP. We covered user-defined functions and a small amount of the pre-defined functions in PHP. Here are some practice exercises to make you comfortable with functions.

Exercise 1

In chapter 2, exercises 2 and 3 you created an associative array that represented a menu and had to output some string based on the contents of the array. We revisit this array in this exercise. Using the same array, create a function that takes three parameters: the menu array, the category selection and meal selection. The function has to output an HTML string. The string should be a paragraph tag containing the content in the following format:

You picked: {name of meal here (in bold)}.

This meal is made from: {list ingredients here (comma-separated list)}.

The nutritional information for this meal is: {list nutritional information here (comma-separated list)}.

Do not use loops! Use the aforementioned string functions to do this.

Exercise 2

This PHP exercise has two parts. For the first, you will create a function to accept two arguments, perform a calculation using them, then return a sentence with the result to the browser. The function will calculate the area of a rectangle, with the two arguments being width and height. (Reminder: area = width * height.) The sentence to be returned is "A rectangle of length $l and width $w has an area of $area.", where $l and $w are the arguments and $area is the result.

Exercise 3

For this PHP exercise, first create an array called $months. Use the names of the months as keys, and the number of days for each month as values. For February, use the following for your value: "28 days, if leap year 29".

Next, write a function to create an option element for a form's select field. Make sure each option will be upper case. Both the array and the function should precede the HTML for the page.

Once again, you will be requesting user input. Create a form for the user with the request, "Please choose a month." Next, provide a select field with the months as options, looping through the array you created and using the function to create the option elements.

When the user clicks the submit button, return the statement "The month of $month has $number days.", where $month is the name of the month the user chose, and $number is the number of days. Be sure to include a different response for February.