Updated November 15, 2009 at 6:24 pm
In our previous tutorial, we covered the basics of defining variables and working with strings. In this tutorial we are going to introduce a few more concepts that will help us manipulate strings and variables.
NULL Value
Sometimes you will no longer have a need for a variable, or you will want to specify a variable's properties without assigning an actual value to it. Both of these situations can take advantage of the null property. Null, much like the English words nil or naught, is used when a variable exists but holds no value. Testing if a variable is null can signal that a certain task has yet to be performed on the variable or that something has changed elsewhere in your program which resulted in the variable losing its value.
Setting a variable to the null type is easy.
$var = null;
Note the lack of quotes. Setting the variable equal to a string with the word "null" is NOT the same as setting a null variable. If you try to print out a null variable, no value will appear on the screen.
PHP Functions
Functional programming led one of the early shifts in computer software design. Functions simplify your program by eliminating redundant code and grouping together code that performs a given task. We are going to explore all of the properties of functions in a later tutorial, but now is a good time to dip our toes in the water.
A function, like a variable, is normally given a name that represents the function's task. Our program will "call" a function, and the function will then perform its task. Sometimes the function will require information input, and we can pass this information to the function through the function's parameters. Often times the parameters will be variables, but this is not a requirement. Sometimes a function will perform a task on its own and we're done with it, and other times the function will return information back to us. This returned information can be saved into a variable, or we can simply ignore it.
Here are two examples of PHP functions:
<?php
$newString = substr("Hello", 1);
ob_start();
?>
The first function above, named substr, has two parameters and returns a value, which is assigned into the $newString variable. In this example, the parameters are a string with the word "Hello," and the number 1. We will examine substr later in this tutorial.
The second function is ob_start. This function returns a true or false value, but since we have no use for this information, we will not assign the return value into a variable. The ob_start function will also accept up to three parameters, but since we have no use for them in this example, we can call the function without sending it any additional information.
PHP API
All programming languages have an application programming interface, known as an API. APIs define the functions and rules necessary for you to interact with the language. Now that we're going to start looking at PHP's functions, I would like to introduce you to PHP's API. The API is an invaluable tool that is easily accessible on PHP's website at
www.php.net . I encourage you to go there now.
In the top right corner of the page you will see a search box with the "function list" option selected. Enter a function name and search to view that function's entry in the API. If you ever have a question about PHP as a language, change the "function list" option to "online documentation" before searching.
Enter the substr function name into the search box and click the arrow. Since development environments are very diverse, it's a good idea to check the API page to make sure the function is available in the version of PHP you are using. Some functions are new and won't work if you are using an older version of the PHP interpreter. Other functions may be deprecated and removed from the language, and you will no longer be able to use these as well.
You will notice that substr has been available since PHP 4 and that it returns a part of a string. The description then lists the function's prototype, which can be thought of as the function's declaration that includes the type of information you will pass to and receive from the function.
You can find substr's prototype below:
string substr ( string $string , int $start [, int $length ] )
The first word is "string," which is the variable type returned. For now, just think of this as the function's result. Next is the function name. Inside the parentheses are the function's parameters. The first is of type string, the second is of type int, and the third is also of type int. Int is short for integer. You will also notice that the $length parameter is enclosed by square brackets ( [ and ] ). Any parameter inside of square brackets is optional.
Please note: If you wish to specify an optional parameter when calling a function, and if there is more than one optional parameter available, you are required to specify every optional parameter to the left of the parameter you want to specify. For example, say the function has optional parameters that are listed [, a [, b [, c ]]]. If you want to specify parameter b, you will also have to include parameter a. You do not have to specify parameter c since c is to the right of b. If you want to specify parameter c, you will have to specify all of the parameters since c is the right-most parameter.
APIs and function prototypes often confuse new programmers since variable names are specified in the prototype. Our substr example includes the parameters $string, $start, and $length. These parameter names were selected to make it easier to understand the type of information passed to the function. These names are simply suggestions; you do not have to name your parameter variables after the prototype. Don't forget, as demonstrated in the substr example earlier in this tutorial, you can pass either a defined variable or a value (i.e. string, number) directly into the function.
Below the function prototype you will find a detailed description of the parameters and their accepted values, the return values, sample code, similar functions, and finally user comments. The user comments can come in handy if there are problems or odd cases pertaining to a certain version of the function. Quirky function behavior may also be listed.
Some Variable Functions and Constructs
Let's take a quick look at a few functions and constructs you may find useful when dealing with variables. A construct works just like a function in most cases. There are limitations on constructs as we will see when we discuss variable functions.
bool isset ( mixed $var [, mixed $var [, $... ]] )
$varIsSet = isset($var1);
The isset construct will check to see if the variables passed in are null. If all of the variables have a value, a Boolean true will be returned. If any of the variables are not set or are null, the construct will return false. Notice how the third parameter is named "$...". This means that you are allowed to pass in as many variables as you would like.
The mixed value before each variable name specifies that the type of variable is irrelevant for that parameter.
void unset ( mixed $var [, mixed $var [, mixed $... ]] )
unset($var1);
The unset construct will destroy a variable. This construct has several uses, but it can come in handy with PHP memory management. Whenever you unset a variable, the space in the computer memory assigned to the variable is freed and can be used by other variables in your script. If your program involves a lot of data manipulation and you no longer need a variable that's holding a lot of data, it is a good practice to unset it.
The unset construct returns a void. This means that no value is returned by the construct.
void var_dump ( mixed $expression [, mixed $expression [, $... ]] )
var_dump($var1, $var2);
The var_dump function can be used if you need to examine a variable's properties. The information displayed includes the type of the variable(s) and its value if the type is not null. The function will print the information to the screen rather than return a value. This output can be controlled, and we will examine that later in the tutorial series.
There are several other variable functions available, and we will explore them as we discuss more advanced topics.
String Manipulation
Some of my most frequently used PHP functions are the built-in string functions. These functions offer all sorts of ways to control string variables. Let's take a look at two of them now.
int strlen ( string $string )
$stringLength = strlen("textinput");
The strlen function simply returns the number of characters present in a string. In the above sample, $stringLength would be equal to nine. Normally you would not pass in text directly, as is demonstrated above. If the text is static and can be counted, it's better to save the known length into the variable directly than to call the function. The less avoidable overhead, the better!
string substr ( string $string , int $start [, int $length ] )
$endOfString = substr($input, 5);
Finally, it's time to examine substr. This function returns a segment of the string you pass in. It does not modify the input string. The second parameter is the starting position, which is the position of the first character you want in your substring.
If you're new to programming, you may not be aware of a little nuance present in most programming languages that also affects PHP and is demonstrated in this substr function. When you first learned to count, you were probably instructed to start with the number one. You'd think the same applies to computer science, but that's not so. Counting almost always starts with the number zero. This applies whenever you are referencing something's position. In this example, the first character of $input would be the 0 start position. If a string has a length of 15 characters, the last character is position 14. It's very easy to get tripped up, and the discrepancy can result in a common "off by one" error which will oftentimes be the source of logic bugs in your program.
The start position you pass to substr can be a negative number. A negative 1 will start the substring at the last position of the string. A negative 5 will start the substring five places from the end of the string.
The third, optional parameter is the length. Since we're not dealing with positions, the length can be treated like any other math figure you are familiar with. A length of five is still five characters. If the length is not specified, the substring will begin at the start position and will end at the termination of the string. If you are taking a substring that starts at position three and has a length of two, the resulting value will be the characters in position three and four.
Here's an example that demonstrates substr.
<?php
$msg = "Hey World";
$first = substr($msg, 0, 3);
$second = substr($msg, 4);
$space = substr($msg, 3, 1);
echo substr($first, 0, 2) . substr($second, 3, 1) . substr($second, 3, 1) . substr($second, 1, 1) . $space . $second . '.';
?>
Can you figure out what this code does? The first line should be obvious by now. We assign the "Hey World" string into $msg. The second line takes a three character long substring of that message, starting with the first character (which is the zero position), and stores it in $first. If you were to print out $first, the message would be "Hey." The next line pulls "World" from the string and stores it in $second.
Notice how we start at position 4, which is really the fifth character. Since we don't specify a length, everything from position 4 onward is a part of the substring. The final substring takes one character from position 3, which is the space.
At this point we have four variables. The msg variable is no longer needed, so we could unset it, but you shouldn't feel inclined to do that since its size is relatively small and thus little memory is taken up.
The final statement is our echo command, which is also a language construct like isset and unset. The echo prints out the concatenated return values of the substrings, the space, the second word, and a period. If you were to run this code, the result would be "Hello World." with the added period. The echo statement as seen above has added efficiency since you aren't creating separate variables for each of the four substrings. You also could have used $msg for all of the substrings rather than creating new variables.
As a final reminder, notice how all of these statements end in semicolons. It's very important that you remember to add the semicolon where it's required as forgetting to do so will result in many unwanted parse errors.
In the next tutorial we will start to look at basic control structures. This will enable us to create worthwhile programs.