Counting Elements in an Array: count, sizeof, and array_count_values We used the function countin an earlier example to count the number of elements in an array of orders.The function si
Trang 192 Chapter 3 Using Arrays
A subtle point to note is the way we pass $value.The ampersand (&) before the vari-able name in the definition of myMultiply()means that $valuewill be passed by
refer-ence Passing by reference allows the function to alter the contents of the array.
We will address passing by reference in more detail in Chapter 5 If you are not famil-iar with the term, for now just note that to pass by reference, we place an ampersand before the variable name
Counting Elements in an Array: count(), sizeof(), and array_count_values()
We used the function count()in an earlier example to count the number of elements in
an array of orders.The function sizeof()has exactly the same purpose Both these functions return the number of elements in an array passed to them.You will get a count
of one for the number of elements in a normal scalar variable and 0 if you pass either an empty array or a variable that has not been set
Thearray_count_values()function is more complex If you call
array_count_values($array), this function counts how many times each unique value
occurs in the array $array (This is the set cardinality of the array.) The function returns
an associative array containing a frequency table.This array contains all the unique values from $arrayas keys Each key has a numeric value that tells you how many times the corresponding key occurs in $array
For example, the following code
$array = array(4, 5, 1, 2, 3, 1, 2, 1);
$ac = array_count_values($array);
creates an array called $acthat contains
This indicates that 4, 5, and 3 occurred once in $array, 1 occurred three times, and 2 occurred twice
Converting Arrays to Scalar Variables: extract()
If we have an associative array with a number of key value pairs, we can turn them into
a set of scalar variables using the function extract().The prototype for extract()is as follows:
Trang 293 Other Array Manipulations
The purpose of extract()is to take an array and create scalar variables with the names
of the keys in the array.The values of these variables are set to the values in the array
Here is a simple example:
$array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');
extract($array);
echo "$key1 $key2 $key3";
This code produces the following output:
value1 value2 value3
The array had three elements with keys:key1,key2, and key3 Using extract(), we created three scalar variables,$key1,$key2, and $key3.You can see from the output that the values of $key1,$key2, and $key3are 'value1','value2', and 'value3', respec-tively.These values came from the original array
There are two optional parameters to extract():extract_typeand prefix.The variable extract_typetells extract()how to handle collisions.These are cases in which a variable already exists with the same name as a key.The default response is to overwrite the existing variable Four allowable values for extract_typeare shown in Table 3.1
Table 3.1 Allowed extract_types for extract()
EXTR_OVERWRITE Overwrites the existing variable when a collision occurs.
EXTR_SKIP Skips an element when a collision occurs.
EXTR_PREFIX_SAME Creates a variable named $prefix_key when a collision
occurs.You must supply prefix
EXTR_PREFIX_ALL Prefixes all variable names with prefix You must supply
prefix
EXTR_IF_EXISTS Only extract variables that already exist (that is, fill existing
variables with values from the array).This was added at version 4.2.0 and is useful for converting, for example, $_REQUEST to
a set of valid variables.
EXTR_PREFIX_IF_EXISTS Only create a prefixed version if the non-prefixed version
already exists.This was added at version 4.2.0.
EXTR_REFS Extract variables as references.This was added at version 4.3.0.
The two most useful options are the default (EXTR_OVERWRITE) and EXTR_PREFIX_ALL The other two options might be useful occasionally when you know that a particular collision will occur and want that key skipped or prefixed A simple example using EXTR_PREFIX_ALLfollows.You can see that the variables created are called prefix-under-score-keyname.
Trang 394 Chapter 3 Using Arrays
$array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); extract($array, EXTR_PREFIX_ALL, 'myPrefix');
echo "$myPrefix_key1 $myPrefix_key2 $myPrefix_key3";
This code will again produce the output:value1 value2 value3 Note that for extract()to extract an element, that element’s key must be a valid variable name, which means that keys starting with numbers or including spaces will be skipped
Further Reading
This chapter covers what we believe to be the most useful of PHP’s array functions.We have chosen not to cover all the possible array functions.The online PHP manual avail-able at http://www.php.net/arrayhas a brief description of each of them
Next
In the next chapter, we look at string processing functions.We will cover functions that search, replace, split, and merge strings, as well as the powerful regular expression func-tions that can perform almost any action on a string
Trang 4String Manipulation and Regular
Expressions
IN THIS CHAPTER,WE’LL DISCUSS HOWyou can use PHP’s string functions to format and manipulate text.We’ll also discuss using string functions or regular expression functions
to search (and replace) words, phrases, or other patterns within a string
These functions are useful in many contexts.You’ll often want to clean up or refor-mat user input that is going to be stored in a database Search functions are great when building search engine applications (among other things)
In this chapter, we will cover
n Formatting strings
n Joining and splitting strings
n Comparing strings
n Matching and replacing substrings with string functions
n Using regular expressions
Example Application: Smart Form Mail
In this chapter, we’ll look at string and regular expression functions in the context of a Smart Form Mail application.We’ll add these scripts to the Bob’s Auto Parts site we’ve been looking at in the last few chapters
This time, we’ll build a straightforward and commonly used customer feedback form for Bob’s customers to enter their complaints and compliments, as shown in Figure 4.1 However, our application will have one improvement over many you will find on the Web Instead of emailing the form to a generic email address like feedback@example com, we’ll attempt to put some intelligence into the process by searching the input for
Trang 596 Chapter 4 String Manipulation and Regular Expressions
key words and phrases and then sending the email to the appropriate employee at Bob’s company For example, if the email contains the word “advertising,” we might send the feedback to the Marketing department If the email is from Bob’s biggest client, it can go straight to Bob
Figure 4.1 Bob’s feedback form asks customers for their name, email address, and comments.
We’ll start with the simple script shown in Listing 4.1 and add to it as we go along
Listing 4.1 processfeedback.php—Basic Script to Email Forms Contents
<?php //create short variable names
$name=$HTTP_POST_VARS['name'];
$email=$HTTP_POST_VARS['email'];
$feedback=$HTTP_POST_VARS['feedback'];
$toaddress = 'feedback@example.com';
$subject = 'Feedback from web site';
$mailcontent = 'Customer name: '.$name."\n"
.'Customer email: '.$email."\n"
."Customer comments: \n".$feedback."\n";
$fromaddress = 'From: webserver@example.com';
mail($toaddress, $subject, $mailcontent, $fromaddress);
?>