Arrays

Arrays offer an ideal means for storing, manipulating, sorting, and retrieving the kinds of data sets that programmers spend a lot of time working with. PHP supports the array data type. This article explains the array-based features and functions it supports. It is excerpted from the book, Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518).

PROGRAMMERS SPEND A considerable amount of time working with sets of related data. The names of all employees at the XYZ corporation, U.S. Presidents and their corresponding birth dates, and years between 1900 and 1975 are all examples of related data sets. Because working with such groups of data is so prevalent, it might not come as a surprise that a means for managing these groups within code is a common feature across all mainstream programming languages. This means typically centers around the compound data type array, which offers an ideal means for storing, manipulating, sorting, and retrieving data sets. PHP’s solution is no different, supporting the array data type, in addition to an accompanying host of behaviors and functions directed towards array manipulation. In this chapter, you’ll learn all about those array-based features and functions supported by PHP. Although it is beyond the scope of this book to provide a comprehensive list of all predefined functions, you’ll nonetheless find information regarding the majority of array functions in this chapter, because PHP’s array-handling capabilities are just so darned useful.

Because I introduce so many functions in this chapter, I thought it wise to divide them into the following categories:

  • Outputting arrays

  • Creating arrays

  • Testing for an array

  • Adding and removing array elements

  • Locating array elements

  • Traversing arrays

  • Determining array size and element uniqueness

  • Sorting arrays

  • Merging, slicing, splicing, and dissecting arrays

Rather than simply list them alphabetically, the categorical division should aid in later reference when searching for a viable solution to some future problem. Before beginning this review, I’ll start the chapter with a brief recap of the array definition and structure.

What Is an Array?

An array is traditionally defined as a group of items that share the same characteristics and are distinguished by their lookup key (more about this key in a bit). I use the word traditionally because you can flaunt this definition and group entirely unrelated entities together in an array structure. PHP takes this a step further, foregoing the requirement that they even share the same datatype. For example, an array might contain items like state names, zip codes, exam scores, or playing card suits. Each entity consists of two items: a key and a value. The key serves as the lookup facility for retrieving its counterpart, the value. These keys can be numerical, and bear no real relation to the value other than the value’s position in the array. As an example, the array could consist of an alphabetically sorted list of state names, with key 0 representing “Alabama”, and key 49 representing “Wyoming”. Using PHP syntax, this might look like this:

$states = array (0 => “Alabama”, “1” => “Alaska”…”49″ => “Wyoming”);

Using numerical indexing, you could reference the first state like so:

$states[0]

NOTE  PHP’s numerically indexed arrays begin with position 0, not 1.

Alternatively, key mappings can be associative, where the key bears some relation to the value other than its array position. Mapping arrays associatively is particularly convenient when using numerical index values just doesn’t make sense. For example, I might want to create an array that maps state abbreviations to their names, like this: OH/Ohio, PA/Pennsylvania, and NY/New York. Using PHP syntax, this might look like:

$states = array (“OH” => “Ohio”, “PA” => “Pennsylvania”, “NY” => “New York”)

You could then reference “Ohio” like so:

$states["OH"]

Arrays consisting solely of atomic entities are referred to as being single-dimensional. Multidimensional arrays consist of other arrays. For example, you could use a multidimensional array to store U.S. state information. Using PHP syntax, it might look like this:

$states = array (
  “Ohio” => array (“population” => “11,353,140”, “capital”
  => “Columbus”),
  “Nebraska” => array(“population” => “1,711,263”,
  “capital” => “Omaha”)
)

You could then reference Ohio’s population like so:

$states["Ohio"]["population"]

This would return the following value:

====================================================
11,353,140
====================================================

In addition to offering a means for creating and populating an array, the language must also offer a means for traversing it. As you’ll learn throughout this chapter, PHP offers many ways for doing so. Regardless of which way you use, keep in mind that all rely on the use of a central feature known as an array pointer. The array pointer acts like a bookmark, telling you the position of the array that you’re presently examining. You won’t work with the array pointer directly, but instead will traverse the array either using built-in language features or functions. Still, it’s useful to understand this basic concept.

{mospagebreak title=Outputting Arrays}

Although it might not necessarily make sense to learn how to output an array before even knowing how to create one in PHP, this function is so heavily used throughout this chapter, and indeed, throughout you daily programming life, that it merits first mention in this chapter.

print_r()

boolean print_r(mixed variable [, boolean return])

The print_r() function takes as input any variable and sends its contents to standard output, returning TRUE on success and FALSE otherwise. This in itself isn’t particularly exciting, until you take into account that it will organize array contents (as well as an object’s) into a very readable format before displaying them. For example, suppose you wanted to view the contents of an associative array consisting of states and their corresponding state capitals. You could call print_r() like this:

print_r($states);

This returns the following:

Array ( [Ohio] => Columbus [Iowa] => Des Moines [Arizona] => Phoenix )

The optional parameter return modifies the function’s behavior, causing it to return the output to the caller, rather than sending it to standard output. Therefore, if you want to return the contents of the above $states array, you just set return to TRUE:

$stateCapitals = print_r($states, TRUE);

This function is used repeatedly throughout this chapter as a simple means for displaying the results of the example at hand.

TIP The print_r() function isn’t the only way to output an array, but rather offers a convenient means for doing so.You’re free to output arrays using a looping conditional (such as while or for), and in fact these sorts of loops are required to implement many application features. I’ll come back to this method repeatedly throughout not only this chapter, but also throughout the entire book.

Creating an Array

Unlike other, much more annoying array implementations of other languages, PHP doesn’t require that you assign a size to an array at creation time. In fact, because it’s a loosely-typed language, PHP doesn’t even require that you declare the array before you use it. Despite the lack of restriction, PHP offers both a formalized and informal array declaration methodology. Each has its advantages, and both are worth learning. We’ll examine both in this section, starting with the informal variety.

You reference the individual elements of a PHP array by denoting the element between a pair of square brackets. Because there is no size limitation on the array, you can create the array simply by making reference to it, like this:

$state[0] = “Delaware”;

You could then display the first element of the array $state like this:

echo $state[0];

You can then add additional values by referencing the intended value in conjunction with the array index, like this:

$state[1] = “Pennsylvania”; 
$state[2] = “New Jersey”;

$state[49] = “Hawaii”;

Interestingly, if you assume the index value is numerical and ascending, you can choose to omit the index value at creation time:

$state[] = “Pennsylvania”;
$state[] = “New Jersey”;

$state[] = “Hawaii”;

Creating associative arrays in this fashion is equally trivial, except that the associative index reference is always required. The following example creates an array that matches U.S. state names with their date of entry into the Union:

$state["Delaware"] = “December 7, 1787″;
$state["Pennsylvania"] = “December 12, 1787″;
$state["New Jersey"] = “December 18, 1787″;

$state["Hawaii"] = “August 21, 1959″;

Next I’ll discuss a functionally identical, yet somewhat more formal means for creating arrays: via the array() function.

array()

array array([item1 [,item2 … [,itemN]]])

The array() function takes as its input zero or more items and returns an array consisting of these input elements. Here is an example of using array() to create an indexed array:

$languages = array (“English”, “Gaelic”, “Spanish”);
// $languages[0] = “English”, $languages[1] = “Gaelic”, $languages[2] = “Spanish”

You can also use array() to create an associative array, like this:

$languages = array (“Spain” => “Spanish”,
                   “Ireland” => “Gaelic”,
                   “United States” => “English”);
// $languages["Spain"] = “Spanish”
// $languages["Ireland"] = “Gaelic”
// $languages["United States"] = “English”

list()

void list(mixed…)

The list() function is similar to array(), though it’s used to make simultaneous variable assignments from values extracted from an array in just one operation. This construct can be particularly useful when you’re extracting information from a database or file. For example, suppose you wanted to format and output information read from a text file. Each line of the file contains user information, including name, occupation, and favorite color, with each piece of information delimited by a vertical bar ( | ). A typical line would look similar to the following:

Nino Sanzi|Professional Golfer|green

Using list(), a simple loop could read each line, assign each piece of data to a variable, and format and display the data as needed. Here’s how you could use list() to make multiple variable assignments simultaneously:

// While the EOF hasn’t been reached, get next line
while ($line = fgets ($user_file, 4096)) {
     // use explode() to separate each piece of data.
     list ($name, $occupation, $color) = explode (“|”, 
     $line);
     // format and output the data
     print “Name: $name <br />”;
     print “Occupation: $occupation <br />”;
     print “Favorite color: $color <br />”;
{

Each line would in turn be read and formatted similar to this:

====================================================
Name: Nino Sanzi
Occupation: Professional Golfer
Favorite Color: green ====================================================

Reviewing the example, list() depends on the function explode()to split each line into three elements, which in turn uses the vertical bar as the element delimiter. The explode() function is formally introduced in Chapter 9. These elements are then assigned to $name, $occupation, and $color. At that point, it’s just a matter of format- ting for display to the browser.

range()

array range(int low, int high [,int step])

The range() function provides an easy way to quickly create and fill an array consisting of a range of low and high integer values. An array containing all integer values in this range is returned. As an example, suppose you need an array consisting of all possible face values of a die:

$die = range(0,6);
// Same as specifying $die = array(0,1,2,3,4,5,6)

The optional step parameter offers a convenient means for determining the increment between members of the range. For example, if you want an array consisting of all even values between 0 and 20, you could use an step value of 2:

$even = range(0,20,2);
// $even = array(0,2,4,6,8,10,12,14,16,18,20);

The range() function can also be used for character sequences. For example, suppose you wanted to create an array consisting of the letters A through F:

$letters = range(“A”,”F”);
// $letters = array(“A,”,”B”,”C”,”D”,”E”,”F”);

{mospagebreak title=Testing for an array}

When you incorporate arrays into your application, you’ll sometimes need to know whether a particular variable is an array. A built-in function, is_array(), is available for accomplishing this task.

is_array()

boolean is_array(mixed variable)

The is_array() function determines whether variable is an array, returning TRUE if it is, and FALSE otherwise. Note that even an array consisting of a single value will still be considered an array. An example follows:

$states = array(“Florida”);
$state = “Ohio”;
echo “$states is an array: “.is_array($states).”<br />”
;
echo “$state is an array: “.is_array($state).”<br />”;

The results are:

====================================================
$states is an array: 1
$state is an array: ====================================================

Adding and Removing Array Elements

PHP provides a number of functions for both growing and shrinking an array. Some of these functions are provided as a convenience to programmers who wish to mimic various queue implementations (FIFO, LIFO, and so on), as reflected by their names (push, pop, shift, and unshift). Even if you don’t know what queue implementations are, don’t worry; these functions are easy to use, and examples are provided for each.

NOTE A traditional queue is a data structure in which the elements are removed in the same order that they were entered, known as first-in-first-out, or FIFO. In contrast, a stack is a data structure in which the elements are removed in the order opposite to that in which they were entered, known as last-in-first-out, or LIFO.

$arrayname[]

This isn’t a function, but a language feature. You can add array elements simply by executing the assignment, like so:

$states["Ohio"] = “March 1, 1803″;

In the case of a numerical index, you can append a new element like this:

$state[] = “Ohio”;

Sometimes, however, you’ll require a somewhat more sophisticated means for adding array elements (and subtracting array elements, a feature not readily available in the fashion described for adding elements). These functions are introduced throughout the remainder of this section.

array_push()

int array_push(array target_array, mixed variable [, mixed variable...])

The array_push() function adds variable onto the end of the target_array, returning TRUE on success and FALSE otherwise. You can push multiple variables onto the array simultaneously, by passing these variables into the function as input parameters. An example follows:

$states = array(“Ohio”,”New York”);
array_push($states,”California”,”Texas”);
// $states = array(“Ohio”,”New York”,”California”,”Texas”);

array_pop()

mixed array_pop(array target_array)

The array_pop() function returns the last element from target_array, resetting the array pointer upon completion. An example follows:

$states = array(“Ohio”,”New York”,”California”,”Texas”); $state = array_pop($states); // $state = “Texas”

{mospagebreak title=Locating Array Elements}

Often, the value of data can be determined by the ability to easily identify items of value, rather than the amount accumulated. If you aren’t able to quickly navigate the information, little good is done accumulating it. In this section, I’ll introduce several functions that enable you to sift through arrays, in an effort to locate items of interest efficiently.

in_array()

boolean in_array(mixed needle, array haystack [,boolean strict])

The in_array() function searches the haystack array for needle, returning TRUE if found, and FALSE otherwise. The optional third parameter, strict, forces in_array() to also consider type. An example follows:

$grades = array(100,94.7,67,89,100);
if (in_array(“100″,$grades)) echo “Somebody studied for the test!”;
if (in_array(“100″,$grades,1)) echo “Somebody studied for the test!”;

Returning:

=====================================================
Somebody studied for the test! =====================================================

This string was output only once, because the second test required that the datatypes match. Because the second test compared an integer with a string, the test failed.

array_keys()

array array_keys(array target_array [, mixed search_value])

The array_keys() function returns an array consisting of all keys located in the array target_array. If the optional search_value parameter is included, only keys matching that value will be returned. An example follows:

$state["Delaware"] = “December 7, 1787″;
$state["Pennsylvania"] = “December 12, 1787″;
$state["New Jersey"] = “December 18, 1787″;
$keys = array_keys($state);
print_r($keys);
// Array ( [0] => Delaware [1] => Pennsylvania [2] => New Jersey )

array_key_exists()

boolean array_key_exists(mixed key, array target_array)

key()

mixed key(array input_array)

The key() function returns the key element located at the current pointer position of input_array. Consider the following example:

$capitals = array(“Ohio” => “Columbus”, “Iowa” => “Des Moines”,”Arizona” => “Phoenix”);
echo “<p>Can you name the capitals of these states?</p>”;
while($key = key($capitals)) {
   echo $key.”<br />”;
   next($capitals);
}

This returns:

====================================================
Ohio
Iowa
Arizona ====================================================

Note that key() does not advance the pointer with each call. Rather, you use the next() function, whose sole purpose is to accomplish this task. This function is formally introduced later in this section.

reset()

mixed reset(array input_array)

The reset() function serves to set the input_array pointer back to the beginning of the array. This function is commonly used when you need to review or manipulate an array multiple times within a script, or when sorting has completed.

each()

array each(array input_array)

The each() function returns the current key/value pair from the input_array, and advances the pointer one position. The returned array consists of four keys, with keys 0 and key containing the key name, and keys 1 and value containing the corresponding data. If the pointer is residing at the end of the array before executing each(), FALSE will be returned.

Array_Walk ()

boolean array_walk(array input_array, callback function [, mixed userdata])

The array_walk() function will pass each element of input_array to the user-defined function. This is useful when you need to perform a particular action based on each array element. Note that if you intend to actually modify the array key/value pairs, you’ll need to pass each key/value to the function as a reference.

The user-defined function must take two parameters as input: the first represents the array’s current value and the second the current key. If the optional userdata parameter is present in the call to array_walk(), then its value will be passed as a third parameter to the user-defined function.

You are probably scratching your head, wondering why this function could possibly be of any use (c’mon, you can admit it). Admittedly, I initially thought the same, until I did a bit of brainstorming. Perhaps one of the most effective examples involves the sanity-checking of user-supplied form data. Suppose the user was asked to provide six keywords that he thought best-described his state. That form source code might look like that shown in Listing 5-1.

Listing 5-1. Using an Array in a Form

<form action=”submitdata.php” method=”post”>
  <p>
   Provide up to six keywords that you believe best 
   describe the state in
   which you live:
   </p>
   <p>Keyword 1:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p>Keyword 2:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p>Keyword 3:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p>Keyword 4:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p>Keyword 5:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p>Keyword 6:<br />
   <input type=”text” name=”keyword[]” size=”20″
   maxlength=”20″ value=”” /></p>
   <p><input type=”submit” value=”Submit!”></p>
</form>

This form information is then sent to some script, referred to as submitdata.php in the form. This script should sanitize user data, then insert it into a database for later review. Using array_walk(), you can easily sanitize the keywords using a function stored in a form validation class:

{mospagebreak title=Determining Array Size and Uniqueness}

A few functions are available for determining the number of total and unique array values. I’ll introduce these functions in this section.

count()

integer count(array input_array [, int mode])

The count() function, quite simply, returns the total number of values found in the input_array. If the optional mode parameter is enabled (set to 1), the array will be counted recursively, a feature useful when counting all elements of a multidimensional array. An example follows:

$locations = array(“Italy”,”Amsterdam”,array(“Boston”,”Des Moines”),”Miami”);
echo count($locations,1);

This returns:

===========================================================
6
===========================================================

You may be scratching your head at this outcome, because there appears to be only five elements in the array. The array entity holding “Boston” and “Des Moines” is counted as an item, just as its contents are.

NOTE The sizeof() function is an alias of count(). It is functionally identical.

array_count_values()

array array_count_values(array input_array)

The array_count_values() function returns an array consisting of associative key/value pairs. Each key represents a value found in the input_array, and its corresponding value denoting the frequency of that key’s appearance (as a value) in the input_array. An example follows:

$states = array(“Ohio”,”Iowa”,”Arizona”,”Iowa”,”Ohio”); $stateFrequency = array_count_values($states);
print_r($stateFrequency);

This returns:

============================================================
Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 ) ============================================================

  • SORT_REGULAR: Sort items by their ASCII value. This means that B will come before a, for instance. Search the Internet for ASCII table to view a comprehensive character ordering.

  • SORT_STRING: Sort items in a fashion that might better correspond with how a human might perceive the correct order. See natsort() for further information about this matter, introduced later in this section.

Consider an example. Suppose you wanted to sort exam grades from lowest to highest:

$grades = array(42,57,98,100,100,43,78,12);
sort($grades);
print_r($grades);

The outcome looks like this:

===========================================================
Array ( [0] => 12 [1] => 42 [2] => 43 [3] => 57 [4] => 78 [5] => 98 [6] => 100 [7] => 100 )
===========================================================

It’s important to note that key/value associations are not maintained. Consider the following example:

$states = array(“OH” => “Ohio”, “CA” => “California”, “MD” => “Maryland”);
sort($states);
print_r($states);

Here’s the output:

===========================================================
Array ( [0] => California [1] => Maryland [2] => Ohio ) ===========================================================

To maintain these associations, use asort(), introduced later in this section.

natsort()

void natsort(array target_array)

The natsort() function is intended to offer a sorting mechanism comparable to those people normally use. The PHP manual offers an excellent example of what is meant by this; Consider the following items: picture1.jpg, picture2.jpg, picture10.jpg, picture20.jpg. Sorting these items using typical algorithms results in the following ordering:

asort()

void asort(array target_array [,integer sort_flags])

The asort() function is identical to sort(), sorting the target_array in ascending order, except that the key/value correspondence is maintained. Consider an array that contains the states in the order in which they joined the Union:

$state[0] = “Delaware”;
$state[1] = “Pennsylvania”;
$state[2] = “New Jersey”

Sorting this array using sort() causes the associative correlation to be lost, which is probably a bad idea. Sorting using sort() and then outputting the results using print_r() results in the following:

===========================================================
Array ( [0] => Delaware [1] => New Jersey [2] => Pennsylvania ) ===========================================================

However, sorting with rsort() results in:

=======================================================
Array ( [0] => Delaware [2] => New Jersey [1] => Pennsylvania ) =======================================================

If you use the optional sort_flags parameter, the exact sorting behavior is determined by its value, as described in the sort() section.

array_multisort()

boolean array_multisort(array array [, mixed arg [, mixed arg2...]])

The array_multisort() function can sort several arrays at once, and can sort multidimensional arrays in a number of fashions, returning TRUE on success and FALSE otherwise. It takes as input one or more arrays, each of which can be followed by flags that determine sorting behavior. There are two categories of sorting flags: order and type. Each flag is described in Table 5-1.

Table 5-1. array_multisort() Flags

FLAG TYPE PURPOSE
SORT_ASC Order Sort in ascending order
SORT_DESC Order Sort in descending order
SORT_REGULAR Type Compare items normally
SORT_NUMERIC Type Compare items numerically
SORT_STRING type Compare items as strings

krsort()

integer krsort(array array [,int sort_flags])

The krsort() function operates identically to ksort(), sorting by key, except that it sorts in reverse (descending) order.

usort()

void usort(array array, callback function_name)

The usort() function offers a means for sorting an array using a user-defined comparison algorithm, embodied within a function. This is useful when you need to sort data in a fashion not offered by one of PHP’s built-in sorting functions.

The user-defined function must take as input two arguments, and must return a negative integer, zero, or a positive integer based on whether the first argument is less than, equal to, or greater than the second argument. Not surprisingly, this function must be made available to the same scope in which usort() is being called.

A particularly applicable example of usort() involves the ordering of American-format dates. Suppose that you want to sort an array of dates in ascending order:

< ->php
$dates = array(’10-10-2003′, ‘2-17-2002′, ‘2-16-2003′, ‘1-01-2005′, ’10-10-2004′);
sort($dates);
// Array ( [0] => 10-01-2002 [1] => 10-10-2003 [2] => 2-16-2003 [3] => 8-18-2002 )
natsort($dates);
// Array ( [2] => 2-16-2003 [3] => 8-18-2002 [1] => 10-01-2002 [0] => 10-10-2003 )
function DateSort($a, $b) {
   // If the dates are equal, do nothing.
   if($a == $b) return 0;
  
// Dissassemble dates
   list($amonth, $aday, $ayear) = explode(‘-‘,$a);
   list($bmonth, $bday, $byear) = explode(‘-‘,$b);
  
// Pad the month with a leading zero if leading number 
   not present
   $amonth = str_pad($amonth, 2, “0”, STR_PAD_LEFT);
   $bmonth = str_pad($bmonth, 2, “0”, STR_PAD_LEFT);
  
// Pad the day with a leading zero if leading number
   not present
   $aday = str_pad($aday, 2, “0”, STR_PAD_LEFT);
   $bday = str_pad($bday, 2, “0”, STR_PAD_LEFT);
  
// Reassemble dates
   $a = $ayear . $amonth . $aday;
   $b = $byear . $bmonth . $bday;

key that already exists in the resulting array, that key/value pair will overwrite the previously existing entry. This behavior does not hold true for numerical keys, in which case the key/value pair will be appended to the array. An example follows:

$face = array(“J”,”Q”,”K”,”A”); 
$numbered = array(“2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″);
$cards = array_merge($face, $numbered);
shuffle($cards);
print_r($cards);

This returns something along the lines of the following (your results will vary because of the shuffle):

Array ( [0] => 8 [1] => 6 [2] => K [3] => Q [4] => 9 [5] => 5 
                               
[6] => 3 [7] => 2 [8] => 7 [9] => 4 [10] => A [11] => J )

array_merge_recursive()

array array_merge_recursive(array input_array1, array input_array2 [, array...])

The array_merge_recursive() function operates identically to array_merge(), joining two or more arrays together to form a single, unified array. The difference between the two functions lies in the way that this function behaves when a string key located in one of the input arrays already exists within the resulting array. array_merge() will simply overwrite the preexisting key/value pair, replacing it with the one found in the current input array. array_merge_recursive() will instead merge the values together, forming a new array with the preexisting key as its name. An example follows:

$class1 = array(“John” => 100, “James” => 85);
$class2 = array(“Micky” => 78, “John” => 45);
$classScores = array_merge_recursive($class1, $class2); print_r($classScores);

This returns the following:

===========================================================
Array ( [John] => Array ( [0] => 100 [1] => 45 ) [James] => 85 [Micky] => 78 ) ===========================================================

Note that the key “John” now points to a numerically indexed array consisting of two scores.

array_slice()

array array_slice(array input_array, int offset [, int length])

The array_slice() function returns the section of input_array starting at the key offset, and ending at position offset + length. A positive offset value will cause the

print_r($states);
print_r($subset);

This returns:

Array ( [0] => Alabama [1] => Alaska [2] => Arizona [3] => Arkansas ) Array ( [0] => California [1] => Connecticut )

You can use the optional parameter replacement to specify an array that will replace the target segment. An illustration follows:

$states = array(“Alabama”, “Alaska”, “Arizona”, “Arkansas”, “California”,
“Connecticut”);
$subset = array_splice($states, 2, -1, array(“New York”, “Florida”));
print_r($states);

This returns the following:

===========================================================
Array ( [0] => Alabama [1] => Alaska [2] => New York [3] => Florida [4] => Connecticut ) ===========================================================

array_intersect()

array array_intersect(array input_array1, array input_array2 [, array...])

The array_intersect() function returns a key-preserved array consisting only of those values present in input_array1 that are also present in each of other the input arrays. An example follows:

$array1 = array(“OH”,”CA”,”NY”,”HI”,”CT”);
$array2 = array(“OH”,”CA”,”HI”,”NY”,”IA”);
$array3 = array(“TX”,”MD”,”NE”,”OH”,”HI”);
$intersection = array_intersect($array1, $array2, $array3); print_r($intersection);

This returns:

===========================================================
Array ( [0] => OH [3] => HI ) ===========================================================

Note that array_intersect() only considers two items to be equal if they also share the same datatype.

array_diff_assoc()

array array_diff_assoc(array input_array1, array input_array2 [, array...])

The function array_diff_assoc() operates identically to array_diff(),except that it also considers array keys in the comparison. Therefore only key/value pairs located in input_array1, and not appearing in any of the other input arrays, will be returned in the result array. An example follows:

$array1 = array(“OH” => “Ohio”, “CA” => “California”, “HI” => “Hawaii”);
$array2 = array(“50″ => “Hawaii”, “CA” => “California”, “OH” => “Ohio”);
$array3 = array(“TX” => “Texas”, “MD” => “Maryland”, “KS” => “Kansas”);
$diff = array_diff_assoc($array1, $array2, $array3); print_r($diff);

This returns:

===========================================================
Array ( [HI] => Hawaii ) ===========================================================

{mospagebreak title=Other Useful Array Functions}

In this section I introduce a number of array functions that perhaps don’t easily fall into one of the prior sections, but are nonetheless quite useful.

array_rand()

mixed array_rand(array input_array [, int num_entries])

The array_rand() function will return one or more keys found in input_array. If you omit the optional num_entries parameter, only one random value will be returned. If num_entries is set to greater than one, that many keys will be returned. An example follows:

$states = array(“Ohio” => “Columbus”, “Iowa” => “Des Moines”,”Arizona” => “Phoenix”);
$randomStates = array_rand($states, 2);
print_r($randomStates);

This returns:

===========================================================
Array ( [0] => Arizona [1] => Ohio ) ===========================================================

array_chunk()

array array_chunk(array input_array, int size [, boolean preserve_keys])

The array_chunk() function breaks input_array into a multidimensional array consisting of several smaller arrays consisting of size elements. If the input array can’t be evenly divided by size, the last array will consist of fewer than size elements. Enabling the optional parameter preserve_keys will preserve each value’s corresponding key. Omitting or disabling this parameter results in numerical indexing starting from zero for each array. An example follows:

$cards = array(“jh”,”js”,”jd”,”jc”,”qh”,”qs”,”qd”,”qc”,
               
“kh”,”ks”,”kd”,”kc”,”ah”,”as”,”ad”,”ac”);
// shuffle the cards
shuffle($cards);
// Use array_chunk() to divide the cards into four equal “hands”
$hands = array_chunk($cards, 4);
print_r($hands);

This returns the following (your results will vary because of the shuffle):

===========================================================
Array ( [0] => Array ( [0] => jc [1] => ks [2] => js [3] => qd )
           [1] => Array ( [0] => kh [1] => qh [2] => jd [3] => kd )
           [2] => Array ( [0] => jh [1] => kc [2] => ac [3] => as )
           [3] => Array ( [0] => ad [1] => ah [2] => qc [3] => qs ) )============================================================

Summary

Arrays play an indispensable role in programming, and are ubiquitous in every imaginable type of application, Web-based or not. The purpose of this chapter was to bring you up to speed regarding many of the PHP functions that will make your programming life much easier as you deal with these arrays.

The next chapter focuses on yet another very important topic: object-oriented programming. This topic has a particularly special role in PHP 5, because the process has been entirely redesigned for this major release.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan