Processing data is accomplished in PHP, as it is in other programming languages, by way of operators and expressions. Operators are the symbols that tell PHP what operations to perform, and expressions are the individual sets of variables and operators that make a result when processing is complete.
PHP Operators
In PHP, you create a variable and set a value to it by using the equal sign, as in:
$my_data = "Hello";
The equal sign is an operator. Operators are used to perform data processing on variable values. In this case, the equal sign is called the assignment operator, because it assigns the string data value to the variable just created.
There are quite a few operators in most programming languages; some of them perform arithmetic, just like you would in a simple equation; some of them operate on string or date data; and some of them perform other functions. They all carry out data processing on variable values.
| Important | Operators that need only one operand are called unary operators; for example, the ++ operator can be appended to the end of a variable name (the operand) to increment the variable by one. Because the ++ operator can be placed before the variable or after the variable, it is said to allow both prefix and postfix notation. Operators that need two operands are called binary operators; the equal sign used in "$my_data = "Hello" is one example. Because the operator is placed between the operands, it is said to be using infix notation. And some languages contain tertiary operators requiring three operands. For example, PHP allows use of the ? operator, which is a shorthand If statement. Such a statement would begin with an expression followed by the question mark, then two possible outcomes separated by a colon ("expression. ? outcome02 : outcome02", meaning "if expression is true then do outcome01, but if not true then do outcome02"). Because the operator is inside the operands, it is also said to use infix notation. |
PHP Expressions
Expressions are any code that evaluates to a value. The assignment of a value to a variable is an expression in itself, although we tend to think of expressions as similar to equations (like $a = $b + $c, where $b + $c is the expression we have in mind).
Therefore, $a = 5 is an expression, because it evaluates to the value 5. If you write $a = $b + $c, you know you're adding $b and $c first, and then setting $a equal to the resulting value. You can make expressions arbitrarily complex (as complex as you'd like) and you can use any of the operators on any appropriate values to get a result. In fact, the main portion of PHP functionality comes from its processing (evaluation) of expressions.
One key part of evaluating an expression, particularly complex expressions, is operator precedence. As in arithmetic or math, it sometimes makes a difference which part of an expression is evaluated first. There is a default precedence of operations, and you can directly control precedence by inserting parentheses. For example, because the multiplication operator (*) has precedence over the addition operator (+), the expression 2 + 2 * 12 results in a value of 26 (2 * 12 is evaluated first, by default, and then added to 2), whereas (2 + 2) * 12 results in a value of 48 (the parentheses force 2 + 2 to be added together first, then the result of that is multiplied by 12).
Operator Types
The following operator types are available in PHP:
| Type | Description |
|---|---|
| Arithmetic | Perform common arithmetical operations, such as addition and subtraction |
| Assignment | Assign values to variables |
| Bitwise | Perform operations on individual bits in an integer |
| Comparison | Compare values in a Boolean fashion (true or false is returned) |
| Error Control | Affect error handling (several new ones in PHP5) |
| Execution | Cause execution of commands as though they were shell commands |
| Incrementing/Decrementing | Increment or decrement a variable |
| Logical | Boolean operators such as AND, OR, and NOT that can be used to include or exclude (more on this in Chapter 4) |
| String | Concatenates (joins together) strings |
| Array | Perform operations (such as append or split) on arrays |
An exhaustive list and reference for each operator aren't provided here because that information is easily available online at www.php.net (just go to the site, click documentation, and you'll find operators listed in the table of contents). When an operator is used in this book, though, some of its peculiarities are discussed.
String Operators and Functions
There is only one string operator: the dot (.), but PHP contains plenty of string functions that enable you manipulate strings effectively. The following sections discuss how the concatenation operator and several of the string functions work.
Using the Concatenation Operator
The concatenation operator (.) can be used between string values to join them together. Here's how it's done in a PHP program:
<?php $first_name = "Joe"; $last_name = "Blow"; $whole_name = $first_name . " " . $last_name; echo "First name plus last name = <b>$whole_name</b>"; ?>
Notice that a space is added to the $whole_name value by concatenating " " (a space between quotes) into the $first_name and $last_name values. There's also a space before and after the concatenation operator each time it's used. This is not necessary, but makes the code a little easier to read. The following code would work just as well:
$whole_name = $first_name." ".$last_name;
To make the answer more readable when displayed in the Web page, HTML tags are added to the echoed response (the <b> and </b> tags to make text bold):
echo "First name plus last name = <b>$whole_name</b>";
Unless you need to include special characters such as quotes in your HTML, you can simply insert the HTML into your text, which will be properly formatted by the browser when the page is displayed. As you can see, the variable $whole_name was simply inserted right into the line of code. In many programming languages it's not possible to do this, but PHP is smart enough to understand that when you use a variable name in a string you want its value—not its name—placed in the string. Of course, if you want the name to be displayed in the string, you must escape the dollar sign (precede the dollar sign with a slash) so PHP knows not to insert the value:
echo "First name plus last name = <b>\ $whole_name</b>";
Using the strien() function
The strlen () function finds the length of a string. It counts all characters in the string and returns the total. In the following example, the total number of characters is placed into the variable named $string_length:
Interestingly, using the concatenation operator to join together a string (such as "The length of the name is") and a numerical value (such as the length of the string contained in $string_length) has the effect of making the entire response a string data type.
The string length function is useful whenever you need a count of the characters in a string, such as when validating data that might go into a database.
Using the strstr() function
The strstr () function gets any part of a string that is after the first instance of a particular character or string within a string. In the next example, the $whole_name variable value (Joe Blow) is searched until the first occurrence of the space character, and then the strstr () function returns everything after that space. Additional occurrences of the search string within the searched string make no difference whatsoever. If the string you seek isn't found within the string being searched, the function returns a value of FALSE.
$part_after_space = strstr($whole_name, " "); echo "The part of the string after the space is <b>" . $part_after_space . "</b>";
Using the strpos() function
The strpos () function is used to determine whether a search string exists within a searched string, and returns a numeric value indicating the location at which the search string begins, if found. In the following example, searching for the string o within the $whole_name value (Joe Blow), returns the position value "1". You might have expected to receive the number 2, because o is the second letter in the name, but like many other programming languages, PHP often uses sets of values starting with 0 rather than 1, so the location is specified as "1".
$letter_position = strpos($whole_name, "o"); echo "The position of the letter "a" is <b>" . $letter_position . "</b>";
In this particular case, PHP is examining the string Joe Blow as though it were an array of characters (which, in fact, it is in PHP), and uses array index values (0,1,2,3,4, and so on) for the location of each character. (There's an "Arrays" section coming up in just a few pages.)
Using the chr() function
The chr () function returns a string character value corresponding to the decimal ASCII value entered as the argument. You can find tables of ASCII characters all over the Internet, and it is often convenient to use them, especially for special characters. For example, the ASCII character for a line feed is 10 and for a carriage return is 13. There really aren't keyboard characters you can enter for these characters, so if you need to include them in a string, you just use chr (10) and chr (13) and the alphabetic characters they represent are inserted into your string.
Try it Out: Work With Strings
Time to create some simple PHP programs that demonstrate how you can use operators in expressions with variables. This program demonstrates working with strings. You'll use the string operator, the dot (.), and several of PHP's built-in string functions. Here's what to do:
- Create a file in any text editor, and save it as working_with_strings.php. Place it in the folder supported by the Web server (if you're working on the machine running the Web server) or upload it to the appropriate folder on the Web server (and upload it again each time you make changes).
- Enter the following code in your file (the screen highlights the PHP portions of code):
<html> <head> <title>Beginning PHP5</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <table width="100%" border="1"> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif"><b>Working With Strings</b></font></td> <td width="51%"> </td> </tr> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1">Using Concatenation - the . operator</font></td> <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $ first_name= "Joe"; $last_name = "Blow" ; $whole_name = $first_name . " " . $last_name; echo "First name plus last name = <b>$whole_name</b>" ; ?> </font></td> </tr> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1"> Finding String Length - using <b>strlen() </b></font></td> <td width="51%" ><font face="Axial. Helvetica. sans-serif" size="-1"> <?php $string_length = strlen ($whole_name) ; echo "The length of the name is <b>" . $string_length . "</b>"; ?> </font></td> </tr> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif" size="- 1">Getting Part of a String - using <b>strstr()</b></font></td> <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $part_after_space = strstr($whole_name, " "); echo "The part of the string after the space is <b>" . $part_after_space "</b>"; ?> </font></td> </tr> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1">Finding Position of Part of a String - using <b>strpos()</b></font></td> <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1"> php $letter_position = strpos($whole_name, "0"); echo "The position of the letter "o" is <b>" . $letter_position . "</b>"; ?> </font></td> </tr> <tr> <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1">Return a character based on an ASCII value - using <b>chr()</b></font></td> <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $ascii_character_returned = chr(97); echo "The character corresponding to ASCII decimal value 97 is <b>" . $ascii_character_returned . "</b>"; ?> </font></td> </tr> </table> </body> </html> - Save the file, upload it if required, and then display it in your browser.
How it Works
The PHP program you just created is embedded in a complete HTML Web page, and within the HTML <body> element the parts of the program are contained within an HTML <table> purely for readability. When the Web page file is requested from the Web server by a browser, the PHP code is parsed and executed, and the results inserted into the HTML stream returned to the browser.
The concatenation operator (.) is used to join string values (including a blank space) together:
<?php $first_name = "Dave"; $last_name = "Mercer"; $whole_name = $first_name . " " . $last_name; echo "First name plus last name = <b>$whole_name</b>"; ?>
The strlen () function finds and returns the length of a string. In this program, it returns a number indicating the count of characters in the string value contained in the $whole_name variable.
The strstr () function finds and returns any part of a string that is after the first instance of a particular character or string within a string. In this program, it searches the $whole_name variable value ("Dave Mercer") until it finds the first occurrence of the space character, and then returns everything after the first space.
The strpos () function finds and returns a number indicating the position within a string or a search string. In this case, searching for the string a within the $whole_name value, returns the position value 1. (Remember that the values start with 0, so the second position is 1.)
The chr () function returns a string character value corresponding to the decimal ASCII value entered as the argument. In this program, the string character for ASCII value 97 is returned.
Arithmetic Operators in PHP
In PHP, the arithmetic operators (plus, minus, and so on) work much as you would expect, enabling you to write expressions as though they were simple equations. For example, $c = $a + $b adds $a and $b and assigns the result to $c. (The = operator is entirely different than the comparison operators = = and = = =, which are discussed in Chapter 4.)
And just like ordinary equations, operator precedence makes a difference, and you can affect this precedence using parentheses. Here's an example;
<?php $first_number = 20; $second_number = 30; $third_number = 3 ; $fourth_number = 2; $total = $first_number * $second_number / $third_number + $fourth_number; $total2 = $first_number * $second_number / ($third_number + $fourth_number); echo "Twenty times thirty divided by three plus two is <b>$total</b><br>"; echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>"; ?>
The difference made by the parentheses is clear when you run the program because the first echo statement returns a value of 202, whereas the second echo statement returns a value of 120.
Special Assignment Operators
The equals sign can be combined with other operators to give you a special assignment operator that makes it easier to write certain expressions. The special assignment operators (such as +=, -=, and so on) simply give you a shorthand method for performing typical arithmetic operations, so that you don't have to write out the variable name multiple times.
For example, you can write
$first_number += $second_number;
rather than
$first_number = $first_number + $second_number;
This also works for other kinds of operators. For example, the concatenation operator can be combined with the equals sign (as . =) so that the current value on the left side is concatenated to the value being assigned on the right, like this:
$a = "Start a sentence "; $b = "and finish it."; $a .= $b //gives Start a sentence and finish it.
The main arithmetic, string, and bitwise operators support combination in this fashion; check the PHP Web site for more information about which operators can be combined like this.
Using the Increment/Decrement Operators
There are often times when it's useful to add or subtract from a number the same amount over and over. This situation occurs so frequently that there are special operators to perform this task: the increment and decrement operators. They are written as two plus signs or two minus signs respectively, preceding or following a variable name, like so:
$a = ++$a; //adds one to $a and then returns the result $a = $a++; //returns $a and then adds one to it $b = --$b; //subtracts one from $b and then returns the result $b = $b--; //returns $b and then subtracts one from it
The location of the operators does make a difference. Placing the operators before the variable name causes the effect (adding or subtracting one) to happen before the value of the variable is returned; placing the operators after the variable name returns the current value of the variable before causing the effect.
Interestingly, you can use the increment and decrement operators in a limited way with characters as well. For example, you can "add"one to the character B and the returned value is C. However, you cannot subtract from (decrement) character values.
Using PHP Math Functions
PHP incorporates many common mathematical functions, including some that require arguments, some that don't require arguments, and some in which arguments are optional. For example, you can use the floor () function to round a number down, no matter what the fractional amount is. But you must provide an argument to the function, otherwise, what would be the point? The argument is the initial value to find the floor for. For example, the find the floor value of 100.01, you'd use a line of code like this:
$a = 100.01; $floor_a = floor($a);
On the other hand, functions like pi () and rand () require no arguments. The pi () function returns the value of pi to 14 decimal places (the default is 14, but your actual precision depends on your setting of the precision directive in your php. ini file). The rand function generates a (pseudo) random number from 1 to RAND_MAX (the maximum number, that varies by operating system), unless you supply it with arguments limiting the range of numbers from which the function can choose.
Try it, Out: Work With Numbers
Here's a little program that demonstrates working with numbers. You'll do some familiar operations, and a few that might not be so familiar, using some of the operators available with PHP, and some of the built-in functions. Once again, you embed your PHP code in HTML so that a Web page can display the results.
- Open your HTML editor and enter the following code. (Although it's good practice for you to enter all of this code, you may instead choose to download the file—working_with_numbers. php—from this book's Web site.)
<html> <head> <title>Beginning PHP5</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <table width="100%" border="1"> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif"><b>Working With Numbers</b></font></td> <td width="43%"> </td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using the Addition Operator ( + ) </font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $first_number = 20; $second_number = 30; $total = $first_number + $second_number; echo "Twenty plus thirty is <b>$total</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using the Increment Operator (++) </font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $first_number = 20; $first_number = ++$ first_number; echo "Twenty incremented by one is <b>$first_number</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using the Multiplication and Division Operators (* and /)</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $first_number = 20; $second_number = 30; $third_number = 3; $fourth_number = 2; $total = $first_number * $second_number / $third_number + $fourth_number; $total2 = $first_number * $second_number / ($third_number + $fourth_number); echo "Twenty times thirty divided by three plus two is <b>$total</b><br>"; echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Special Assignment Operators - Using += and *=</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $first_number = 20; $second_number = 30; $total = $first_number += $second_number; $total2 = $first_number *= $second_number; echo "Twenty plus_equals thirty is <b>$total</b><br>"; echo "Twenty time_equals thirty is <b>$total2</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l"> Getting the absolute value of a number - Using abs () </font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $frist_number = -2.7; echo "The absolute value of 2.7 is <b>" . abs($first_number) . "</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1"> Converting a binary number to a decimal number - Using bindec()</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $binary..number = 10101111; $decimal_number = bindec ($binary_number) ; echo "The decimal equivalent of the binary number 10101111 is <b>$decimal_number</b>" ; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Round Numbers up or down - Using ceil () and floor ()</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> < ?php $first_number = 2.4; echo "2.4 rounded up is <b>" . ceil (first_number) . "</b> and rounded down is <b>" . floor ($first_number) . "</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l">Finding the maximum or minimum value - Using max( ) and min( )</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $max_value = max(2,3,4); $min_value = min(2,3,4); echo "The max value of 2,3,4 is <b>" , $max_value . "</b>, and the min value is <b>" . $min_value , "</b>"; ?> /font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Get the value of PI - Using pi ( ) </font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php echo "The value ot PI is <b>" . pi( ) . "</b>"; ?> </font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l">Get a random number - Using rand( ) </font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php echo "A random number is <b>" . rand() . "</b>"; ?> /font></td> </tr> <tr> <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Get the square root - Using sqrt()</font></td> <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1"> <?php $first_number = 20; echo "The square root of twenty is <b>" . sqrt($first_number) . "</b>"; ?> </font></td> </tr> </table> </body> </html>
How it Works
You use the same format for displaying results in this program as you did with the last. This program demonstrates some simple calculations with operators, some basic use of built-in functions, and the results of several built-in functions that take no arguments (such as pi()).
In the code you set some values and then processed them with different sets of parentheses to illustrate how operator precedence works:
<?php $first_number = 20; $second_number = 30; $third_number = 3; $fourth_number = 2; $total = $first_number * $second_number / $third_number + $fourth_number; $total2 = $first_number * $second_number / ($third_number + $fourth_number); echo "Twenty times thirty divided by three plus two is <b>$total</b><br>"; echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>"; ?>
Then increment and decrement operators were used to add or subtract one from the numerical value contained in the variables $a and $b.
$a = ++$a; //adds one to $a and then returns the result $a = $a++; //returns $a and then adds one to it $b = --$b; //subtracts one from $b and then returns the result $b = $b--; //returns $b and then subtracts one from it
The use of the pi () and rand () functions demonstrates how to make PHP generate values for pi or that are random. Just write out the function with no arguments in between the parentheses, and that's all there is to it (other than using the equals sign to assign the value to a variable).
Arrays
Arrays are variables of type array (notice array is referred to as a data type), so you might be wondering why there's a whole section of this chapter for them. Yes, arrays are variables, but they are very special and powerful variables, and so deserve their own section.
Technically, arrays are lists made up of keys (the indexes) and values, which are the values contained in each element. Elements are the value containers in an array. You can think of an element as being similar to a separate variable, and being made up of a name/value pair.
Although some books imply that arrays can be very complex and hard to grasp, there's an easy way to think about them comfortably: Arrays are variables with many value containers, and several ways to access any particular value. They are almost like mini relational databases that are dynamic, in that they reside in memory only as long as the current program is executing (unless you store them in the session or in a real database between page requests). Array names are like the names of tables in a database, and an array container that contains another array is like a related table in a database. This analogy is not precise, but it can be very helpful when thinking about how to create or access arrays and their values.
Array Indexes
The array () function (actually, it is a language construct, not a function, but is written the same way as a function) is used to create an array, and accepts as arguments the values you want to place in the array. An element in an array can be accessed by its index number. An index number is like a little address by which you can access that particular variable spot within an array. Because all the variable spots in an array begin with the name of the array, each particular spot must have its own unique number. Index numbers for arrays begin with zero (0). For example, in the following line of code, the $my_array variable is set equal to an array that has four elements numbered 0, 1, 2, and 3:
$my_array = array ("cat", "dog", "horse", "goldfish");The variable $my_array is set to the result of the array () function. If you ran the is_array () function on $my_var, the result would be true, indicating that, sure enough, $my_var is structured as an array.
To access the values in the array just created, you can use code such as the following:
$zero_element = $my_array[0]; $one_element = $my_array[1]; $two_element = $my_array[2]; $three_element = $my_array[3];
Using Strings as Array Indexes
Because you can use arrays in so many situations, it's often helpful to give elements a name rather than simply let them adopt the next number (starting with 0) in sequence. For example, the following code produces an array in which each element has a string as a name, and then sets a series of variables to the values of each named string:
$my_named_array = array("dog" => "rover", "cat" => "pinky", "hamster" =>
"fluffball");
$my_dog = $my_named_array["dog"];
$my_cat = $my_named_array["cat"];
$my_hamster = $my_named_array["hamster"];
echo "My dog is named $my_dog, my cat is named $my_cat,
and my hamster is named $my_hamster";The capability to access a value by name is important because you don't need to have any idea what the sequence of values or the actual index number is—you only need to know the name you gave to that element. When using strings as array indexes, it's best to use quotes around the array names. Although it's easy and convenient to leave the quotes off, the online documentation warns against this practice, anticipating the time when the quotes become mandatory and not using quotes will break your code.
If you wanted to, you could still use the index number instead of the names you've assigned, because PHP arrays always keep index numbers as well as any assigned names, so the following code would work exactly the same as the last example:
Initializing Arrays
You can initialize (create and set initial values for) arrays in a number of ways. For example, you can use the array () function, as you've already done or you can end a variable name with square brackets ([]). Writing a variable name and placing empty square brackets at the end causes PHP to decide that you intend to create an array, and to begin to increment the index from zero if it is the first element in the array, as shown here:
$my_array[] = "first element";
If you want to give the element a name, just put it inside the square brackets, like so:
$my_array["first"] = "another_first element";If you used $my_array [" first" ] again, PHP would overwrite the value you just assigned instead of creating a new element. If you use $my_array [ ] again, PHP would assign an index number (the next one in sequence) and create a new element on your array.
An interesting thing about arrays: a single array can hold many different values, each of a different type as required by your program (the indexes for each element can be only strings or integers). This means you really can use an array to hold data much like a record in a database table holds data.
Working with Arrays
Sometimes after creating and initializing an array (especially with values from a record in a database table) it can be a bit difficult to know what those values might be, and therefore hard to debug your code. Fortunately, the print_r() function enables you to print out the entire list contained in an array, along with the names of each indexed element. To follow along with this example, create a simple HTML page and embed the following PHP code in it:
<?php $my_named_array = array("dog" => "rover", "cat" => "pinky", "hamster" => "fluffball"); print_r($my_named_array) ; ?>
Using print_r is very helpful if you want to look at all the contents of an array. In Chapter 4 you'll learn about specialized loops, which also provide very easy access to all the values in an array.
Arrays are real workhorses in PHP, as in many other languages, and PHP comes complete with many built-in functions specifically for working with arrays. You'll explore a couple of the most used functions here, and begin to work with them more in Chapters 3 and 4; you'll notice that many of them are similar to functions you can use on databases.
There are often times when you don't know how many elements are in an array, but you can use the count () function to count them (or the elements in any variable for that matter), like this:
The array_count_values () function is not quite the same, because it returns (as an array) the frequency of occurrence of matching values in the array used as an argument to it. The element names in $returned_array are the values in $argument_array, and the values in $returned_array are the number of times the value occurred in the $argument_array. This may be this easier to understand by reading the following code:
$argument_array = array("dog", "dog" "cat", "cat", "hamster");
$returned_array = array_count_values($argument_array);
print_r($returned_array);This prints out:
Array
(
[dog] => 2
[cat] => 2
[hamster] => 1
)The array_f1ip() function is useful when you need to swap values for key names and vice versa. For example, if you have a list of people's names as element names in an array, and the value of each is a SSN (Social Security number), you may want to flip the array so you can access each person by his SSN (because the SSN should be unique, although their names may be duplicated in some cases). You could accomplish this using the following code:
$my_people_array = array("John" => "555-66-7777", John => "444-55-3333");
$my_ssn_array = array_flip($my_people_array);You could then use $my_ssn_array to look people up uniquely, even though John appears twice.
Sorting Arrays With sort() and asort()
It's often convenient to sort the elements in an array, such as when you want to produce a list of names in alphabetical order, and you can do just that with the sort () function. If you want to maintain the order of the indexes, use asort (). The sort function rebuilds the indexes into the proper order whereas changing the order of the element values, but asort () keeps the indexes stuck to their element values. The code can be written:
$my_unsorted_array = array("Jim", "Bob", "Mary"); $my_sorted_array = sort($my_unsorted_array); $my_sorted_array_with_unchanged_indexes = asort($my_unsorted_array);
