This can be fixed by concatenating the strings as follows: Mixing Elements in an Array The index/key value in an array can be a positive or negative number or a string, and the value as
Trang 1A parse error occurred because single quotes were embedded within double quotes This can be fixed by concatenating the strings as follows:
Mixing Elements in an Array
The index/key value in an array can be a positive or negative number or a string, and the value associated with it can be
a string, a number, another array, and so on If an index value is not given, PHP provides a numeric index, incrementing the index of the next position in the array by 1
Example 8.7 demonstrates how the index and the value of the elements can be mixed The output is shown in Figure 8.11
3 echo "\$colors[-1] is " $colors[-1] ".<br />";
4 echo "\$colors[0] is $colors[0].<br />";
echo "\$colors[1] is $colors[1].<br />";
5 echo "\$colors['brown'] is " $colors['brown'] ".<br />";
6 // echo "\$color['brown'] is {$colors['brown']}<br />";
Trang 2'orange' 'orange'
"brown" "burnt sienna"
Figure 8.11 Mixed array elements Output from Example 8.7
8.1.3 Printing an Array
There are a number of ways to print the contents of an array PHP provides built-in functions to display all of the keys and values, or you can use loops We discuss the built-in functions first
The print_r() Function
The print_r() built-in function displays detailed information about a variable, such as its type, length, and contents
It displays the value of a string, integer, or float In the case of arrays, print_r() displays all of the elements of an array; that is, the key–value pairs (Use the HTML <pre> tag, to display each element on a separate line; otherwise, the output is displayed on one line.) If you would like to capture the output of print_r() in a variable, set the return parameter to boolean TRUE The print_r() function can also be useful when debugging a program
Remember that print_r() will move the internal array pointer to the end of the array Use reset() to bring it back
to the beginning PHP 5 appears to reset the pointer automatically after using print_r()
Example 8.8 demonstrates the print_r() function The output is shown in Figure 8.12
Trang 3<pre>
print_r()
Trang 4Figure 8.12 Printing an array with the print_r() function Output from Example 8.8
</pre>
</body>
</html>
Trang 5Figure 8.13 Saving the output from print_r() in a variable Output from Example 8.9
The var_dump() Function
The var_dump() function displays the array (or object), the number of elements, and the lengths of each of the string values It also provides output with indentation to show the structure of the array or object (See Chapter 17, “Objects,” for more on objects.)
Example 8.10 demonstrates the var_dump() function The output is shown in Figure 8.14
Format
void var_dump ( mixed expression [, mixed expression [, ]] )
Example:
$states=array('CA' => 'California','MT'=>'Montana','NY'=>'New York');
var_dump($states); // Dumps output in a structured format
Example 8.10
<html>
<head><title>The var_dump() Function</title></head>
<body bgcolor="CCFF99">
Trang 7Figure 8.14 Printing an array with the var_dump() function Output Example 8.10
8.1.4 Using Loops to Access Array Elements
Loops make it easy to step through an array The for and while loops are useful for numeric arrays where you can determine the size, and starting point of the array is usually 0, incremented by 1 for each element The best way to loop through an associative array is with the foreach loop, although you can use this loop for numerically indexed arrays
as well
The for Loop
The for loop can be used to iterate through a numeric array The initial value of the for loop will be the first index value of the array, which will be incremented each time through the loop until the end of the array is reached
Example 8.11 demonstrates how the for loop is used to view each element of an array The output is displayed in Figure 8.15
Trang 8$i
$colors
Figure 8.15 Using the for loop to loop through an array Output from Example 8.11
The while Loop
The while loop can be used to iterate through a numeric array as shown in Examples 8.12 and 8.13
By setting the initial value to 0, the loop will iterate from the first element of the array (assuming that the array starts at element zero) until it reaches the end of the array The count() or sizeof() functions can be used to find the length of the array
Trang 10Figure 8.16 Using the while loop to iterate through an array Output from Example 8.12
Trang 116 $i++; // Increment the value of the loop counter
7 }
?> </body>
Figure 8.17 The while loop and arrays Output from Example 8.13
The foreach Loop
The foreach statement is designed to work with both numeric and associative arrays (works only on arrays) The loop expression consists of the array name, followed by the as keyword, and a user-defined variable that will hold each successive value of the array as the loop iterates The expression in the foreach statement can include both the key and value as shown in Example 8.14 The foreach loop operates on a copy of the original array If you change the value of an element of the array, it will only change the copy, not the value in the original
Trang 12Format
(Numeric Array)
foreach ($array_name as $value){
do-something with the element's value;
$suit=("diamond", "spade", "club", "heart");
foreach ( $suit as $card_type){
echo $card_type "<br />"; // displays: diamond
}
spade
club heart (Associative Array)
foreach ($array_name as $key => $variable){
do-something $key and/or $variable;
foreach ( $courses as $number=>$class_name){
echo $number '=>' $class_name "<br />"; // displays keys
// and values }
1 $colors=array('red','green', 'blue', 'yellow');
2 $employee=array('Name' => 'Jon Doe',
'ID' => '23d4',
'Job Title'=> 'Designer',
'Department'=>'Web Development',
Trang 134 foreach ($employee as $key => $value){// Associative array
echo "employee[$key] => $value<br />";
Trang 14Modifying a Value by Reference with a foreach Loop
As of PHP 5, you can easily modify an array’s elements by preceding the value after the as keyword with & This will assign by reference instead of copying the value; that is, whatever you do to the array while in the loop will change the original array, not a copy of it
Trang 15exits
print_r()
Figure 8.19 Modifying values by reference Output from Example 8.15
8.1.5 Checking If an Array Exists
PHP makes it possible to check to see if an array exists, and to check for the existence of keys, values, or both See
Trang 16Example 8.16 demonstrates how to perform array checks using the functions in Table 8.2 The output is displayed in Figure 8.20
$states array_key_exists()
in_array()
"Montana" $states
Trang 17Figure 8.20 Checking an array’s existence
8.1.6 Creating Strings from Arrays and Arrays from Strings
In Chapter 6, “Strings,” we discussed strings and their many functions Now that we have learned about arrays, PHP provides functions that serve the dual purpose of creating arrays from strings and strings from arrays (see Table 8.3)
Table 8.3 Arrays and Strings
explode()
implode()
split()
The implode() Function
The implode() function creates a string by joining together the elements of an array with a string delimiter, called the glue string As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string("") Another name for implode() is its alias, join()
The implode() function returns a string containing a string representation of all the array elements in the same order, with the glue string between each element
Format
string implode ( string glue, array elements )
Example:
$stats_array = array('name', 'ssn', 'phone'); // implode() creates a string from
an array $stats_string = implode(",", $array);
The explode() Function
The explode() function splits up a string and creates an array, the opposite of implode() The new array is created by splitting up the original string into substrings based on the delimiter given The delimiter is what you
determine is the word separator, such as a space or comma If given a limit, the new array will be limited to that many substrings, and the last one will contain the rest of the string See also “The preg_split() Function—Splitting Up
Strings” on page 510
Trang 18Example 8.17 demonstrates how the explode function works Its output is displayed in Figure 8.21
Format
array explode(string separator, string string [, int limit])
Example:
$fruit = explode(" ", "apples pears peaches plums") //Creates a 4-element array
$fruit = explode("|", "apples|pears|peaches|plums",3) echo $fruit[0],
$fruit[1], $fruit[2]; // Creates a 3-element array
1 $colors="red green orange blue";// Create a string
2 echo "<b>\$colors is a " gettype($colors)."\n";
3 $colors=explode(" ",$colors);// Split up the string by
spaces
echo "<img src='explosion.jpg'>","\n";
4 echo "<b>After explode():\$colors is an "
gettype($colors)."\n";
print_r($colors);
// Let's give explode() second parameter limiting
// array size to 3 elements
5 $colors=explode(" ","red green orange blue",3);
Trang 19Figure 8.21 Converting a string to an array with the explode() function Output from Example 8.17
8.1.7 Finding the Size of an Array
PHP provides built-in functions to count the number of elements in an array They are count(), sizeof(), and array_count_values() Example 8.18 demonstrates how to find the size of a multidimensional array
Table 8.4 Functions to Find the Size of an Array
The count() and sizeof() Functions
The count() [2] and sizeof() functions do the same thing: They both return the number of elements in an array (or properties in an object) To find the number of elements in a multidimensional array, the count() function has an optional mode argument that recursively counts the elements
[2] The sizeof() function is simply an alias for the count() function
Format
$number_of_elments =count(array_name); $number_of_elements=count(array_name, 1);
$number_of_elements=count(array_name, COUNT_RECURSIVE)
Trang 20Figure 8.22 Finding the size of an array Output from Example 8.18
The array_count_values() Function
The array_count_values() function counts how many times a unique value is found in an array It returns an associative array with the keys representing the unique element of the array, and the value containing the number of times that unique element occurred within the array
Format
array array_count_values ( array input )
Example:
$hash_count = array_count_values( array("a","b", "a","a")); // Creates an
associative array with "a" and "b" as the two keys and // the number of times each occurs in the array (the associated value)
Trang 21"blue" "green" "yellow"
"green" "yellow"
print_r() array_count_values()
Figure 8.23 The array_count_values() function Outpuf from Example 8.19
Trang 228.1.8 Extracting Keys and Values from Arrays
PHP provides functions that allow you to extract elements from an array and assign the keys and values to variables The array_keys() function returns all the keys in an array, the array_values() function returns all the values
of the elements in an array, and the each() function can be used to extract both keys and values
The array_keys() Function
The array_keys() function returns all the keys of an array If the optional search_value argument is specified, you can get the keys for that particular value See Example 8.20
$colors=array("red", "green", "blue", "yellow");
print"The original array:<br />";
Trang 24Figure 8.24 Getting the keys from an array Output from Example 8.2
Trang 25The array_values() Function
The array_values() function returns an array with all the values of the original array The new array is indexed by numbers See Example 8.21 and Figure 8.25 for its output
1 $colors=array("red", "green", "blue", "yellow");
print"The original array:<br />";
Trang 26Explanation
$colors array_values()
$poem array_values()
$poem
Trang 27Figure 8.25 Getting the values from an array Output from Example 8.21
Trang 28The each() Function
The each() function returns the current key–value pair in an array, and moves to the next element, making that the current element The returned value is an array of two alternating values to represent each key and its corresponding value To access the array elements, you can use either 0 and 1 to represent each key and value, or the keywords key and value to do the same thing Used with a looping construct, each element of the array can be accessed until the array has reached its end The reset() function sets the internal array pointer back to the beginning of the array if you want to access the array elements again See Example 8.22
// echo $array[0]." => " $array[1] "<br />";
3 echo $array['key']." => " $array['value'] "<br />"; }
4 $book=array('Title' => 'War and Peace',
6 echo $novel[0]."=> " $novel[1]."<br />";
// echo $novel['key']." => " $novel['value'] "<br />";
Trang 29Figure 8.26 Getting both keys and values from an array Output from Example 8.22
8.1.9 Creating Variables from Array Elements
The list() and extract() functions create variables from numeric and associative arrays, respectively
The list() Function and Numeric Arrays
Trang 30The list() function extracts elements from a numeric array (with index starting at 0) and assigns them to individual variables The list() function is on the left side of the assignment operator Its arguments are a comma-separated list
of variable names The variables created by list() correspond to the array elements on the right side of the
assignment operator If there are less variables than array elements, the extra elements are ignored
[3] Technically, although list() acts like a function, it is a language construct with no return value
The list() and each() functions work nicely together when iterating through an associative array (see Example 8.23)
Format
void list ( mixed varname, mixed )
Example:
$swatch = array('blue', '#33A1C9', 'peacock'); list($color, $code, $name) =
$swatch; // Create variables from array list($color, $code) = $swatch; // Ignore 'peacock' list($color, , $name)=$swatch; // Skip '#33A1C9'
1 $colors=array("red", "green", "blue");
2 list($a,$b)=$colors;// Create two variables, $a and $b
echo "The list() function assigns array elements to
5 while( list($key, $val) = each($book)){
echo "$key => $val<br />";