<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="http://commons.oreilly.com/wiki/skins/common/feed.css?97"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;action=history&amp;feed=atom</id>
		<title>PHP Cookbook/Arrays - Revision history</title>
		<link rel="self" type="application/atom+xml" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;action=history&amp;feed=atom"/>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;action=history"/>
		<updated>2013-05-22T17:41:16Z</updated>
		<subtitle>Revision history for this page on the wiki</subtitle>
		<generator>MediaWiki 1.11.0</generator>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=26128&amp;oldid=prev</id>
		<title>Newacct: /* Checking if a Key Is in an Array */</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=26128&amp;oldid=prev"/>
				<updated>2010-01-29T22:32:16Z</updated>
		
		<summary type="html">&lt;p&gt;&lt;span class=&quot;autocomment&quot;&gt;Checking if a Key Is in an Array&lt;/span&gt;&lt;/p&gt;

			&lt;table style=&quot;background-color: white; color:black;&quot;&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;tr&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;←Older revision&lt;/td&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;Revision as of 22:32, 29 January 2010&lt;/td&gt;
			&lt;/tr&gt;
		&lt;tr&gt;&lt;td colspan=&quot;2&quot; class=&quot;diff-lineno&quot;&gt;Line 753:&lt;/td&gt;
&lt;td colspan=&quot;2&quot; class=&quot;diff-lineno&quot;&gt;Line 753:&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt; if (isset($array['key'])) { /* there is a value for 'key' in $array */ }&lt;/div&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt; if (isset($array['key'])) { /* there is a value for 'key' in $array */ }&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class='diff-marker'&gt;+&lt;/td&gt;&lt;td style=&quot;background: #cfc; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class='diff-marker'&gt;+&lt;/td&gt;&lt;td style=&quot;background: #cfc; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;Or &amp;lt;tt&amp;gt;array_key_exists( )&amp;lt;/tt&amp;gt; :&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class='diff-marker'&gt;+&lt;/td&gt;&lt;td style=&quot;background: #cfc; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class='diff-marker'&gt;+&lt;/td&gt;&lt;td style=&quot;background: #cfc; color:black; font-size: smaller;&quot;&gt;&lt;div&gt; if (array_key_exists('key', $array)) { /* there is a value for 'key' in $array */ }&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;=== Discussion ===&lt;/div&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;=== Discussion ===&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan=&quot;2&quot; class=&quot;diff-lineno&quot;&gt;Line 760:&lt;/td&gt;
&lt;td colspan=&quot;2&quot; class=&quot;diff-lineno&quot;&gt;Line 764:&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;=== See Also ===&lt;/div&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;=== See Also ===&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt;-&lt;/td&gt;&lt;td style=&quot;background: #ffa; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;Documentation on &amp;lt;tt&amp;gt;isset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/isset''.&lt;/div&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt;+&lt;/td&gt;&lt;td style=&quot;background: #cfc; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;Documentation on &amp;lt;tt&amp;gt;isset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/isset&lt;ins style=&quot;color: red; font-weight: bold; text-decoration: none;&quot;&gt;'' and &amp;lt;tt&amp;gt;array_key_exists( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array_key_exists&lt;/ins&gt;''.&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;== Checking if an Element Is in an Array ==&lt;/div&gt;&lt;/td&gt;&lt;td class='diff-marker'&gt; &lt;/td&gt;&lt;td style=&quot;background: #eee; color:black; font-size: smaller;&quot;&gt;&lt;div&gt;== Checking if an Element Is in an Array ==&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;!-- diff cache key wikicontent:diff:version:1.11a:oldid:7316:newid:26128 --&gt;
&lt;/table&gt;</summary>
		<author><name>Newacct</name></author>	</entry>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=7316&amp;oldid=prev</id>
		<title>Docbook2Wiki: Initial conversion from Docbook</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=7316&amp;oldid=prev"/>
				<updated>2008-03-07T13:36:04Z</updated>
		
		<summary type="html">&lt;p&gt;Initial conversion from Docbook&lt;/p&gt;

			&lt;table style=&quot;background-color: white; color:black;&quot;&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;tr&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;←Older revision&lt;/td&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;Revision as of 13:36, 7 March 2008&lt;/td&gt;
			&lt;/tr&gt;
		&lt;/table&gt;</summary>
		<author><name>Docbook2Wiki</name></author>	</entry>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=3111&amp;oldid=prev</id>
		<title>Evanlenz: 1 revision(s)</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=3111&amp;oldid=prev"/>
				<updated>2008-03-06T22:30:00Z</updated>
		
		<summary type="html">&lt;p&gt;1 revision(s)&lt;/p&gt;

			&lt;table style=&quot;background-color: white; color:black;&quot;&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;tr&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;←Older revision&lt;/td&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;Revision as of 22:30, 6 March 2008&lt;/td&gt;
			&lt;/tr&gt;
		&lt;/table&gt;</summary>
		<author><name>Evanlenz</name></author>	</entry>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=3110&amp;oldid=prev</id>
		<title>Docbook2Wiki: Initial conversion from Docbook</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Arrays&amp;diff=3110&amp;oldid=prev"/>
				<updated>2008-03-06T22:28:45Z</updated>
		
		<summary type="html">&lt;p&gt;Initial conversion from Docbook&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{PHP Cookbook/TOC}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Arrays are lists: lists of people, lists of sizes, lists of books. To store a group of related items in a variable, use an array. Like a list on a piece of paper, the elements in array have an order. Usually, each new item comes after the last entry in the array, but just as you can wedge a new entry between a pair of lines already in a paper list, you can do the same with arrays in PHP.&lt;br /&gt;
&lt;br /&gt;
In many languages, there is only one type of array: what is called a ''numerical array'' (or just an array). In a numerical array, if you want to find an entry, you need to know its position within the array, known as an ''index''. Positions are identified by numbers: they start at 0 and work upwards one by one.&lt;br /&gt;
&lt;br /&gt;
In some languages, there is also another type of array: an ''associative array'' , also known as a ''hash'' . In an associative array, indexes aren't integers, but strings. So, in a numerical array of U.S. presidents, &amp;quot;Abraham Lincoln&amp;quot; might have index 16; in the associative-array version, the index might be &amp;quot;Honest.&amp;quot; However, while numerical arrays have a strict ordering imposed by their keys, associative arrays frequently make no guarantees about the key ordering. Elements are added in a certain order, but there's no way to determine the order later.&lt;br /&gt;
&lt;br /&gt;
In a few languages, there are both numerical and associative arrays. But, usually the numerical array &amp;lt;tt&amp;gt;$presidents&amp;lt;/tt&amp;gt; and the associative array &amp;lt;tt&amp;gt;$presidents&amp;lt;/tt&amp;gt; are distinct arrays. Each array type has a specific behavior, and you need to operate on them accordingly. PHP has both numerical and associative arrays, but they don't behave independently.&lt;br /&gt;
&lt;br /&gt;
In PHP, numerical arrays ''are'' associative arrays, and associative arrays ''are'' numerical arrays. So, which kind are they really? Both and neither. The line between them constantly blurs back and forth from one to another. At first, this can be disorienting, especially if you're used to rigid behavior, but soon you'll find this flexibility an asset.&lt;br /&gt;
&lt;br /&gt;
To assign multiple values to an array in one step, use &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');&lt;br /&gt;
&lt;br /&gt;
Now, the value of &amp;lt;tt&amp;gt;$fruits[2]&amp;lt;/tt&amp;gt; is &amp;lt;tt&amp;gt;'Cantaloupes'&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; is very handy when you have a short list of known values. The same array is also produced by:&lt;br /&gt;
&lt;br /&gt;
 $fruits[0] = 'Apples';&lt;br /&gt;
 $fruits[1] = 'Bananas';&lt;br /&gt;
 $fruits[2] = 'Cantaloupes';&lt;br /&gt;
 $fruits[3] = 'Dates';&lt;br /&gt;
&lt;br /&gt;
and:&lt;br /&gt;
&lt;br /&gt;
 $fruits[ ] = 'Apples';&lt;br /&gt;
 $fruits[ ] = 'Bananas';&lt;br /&gt;
 $fruits[ ] = 'Cantaloupes';&lt;br /&gt;
 $fruits[ ] = 'Dates';&lt;br /&gt;
&lt;br /&gt;
Assigning a value to an array with an empty subscript is shorthand for adding a new element to the end of the array. So, PHP looks up the length of &amp;lt;tt&amp;gt;$fruits&amp;lt;/tt&amp;gt; and uses that as the position for the value you're assigning. This assumes, of course, that &amp;lt;tt&amp;gt;$fruits&amp;lt;/tt&amp;gt; isn't set to a scalar value, such as 3, and isn't an object. PHP complains if you try to treat a nonarray as an array; however, if this is the first time you're using this variable, PHP automatically converts it to an array and begins indexing at 0.&lt;br /&gt;
&lt;br /&gt;
An identical feature is the function &amp;lt;tt&amp;gt;array_push( )&amp;lt;/tt&amp;gt; , which pushes a new value on top of the array stack. However, the &amp;lt;tt&amp;gt;$foo[ ]&amp;lt;/tt&amp;gt; notation is the more traditional PHP style; it's also faster. But, sometimes, using &amp;lt;tt&amp;gt;array_push( )&amp;lt;/tt&amp;gt; more accurately conveys the stack nature of what you're trying to do, especially when combined with &amp;lt;tt&amp;gt;array_pop( )&amp;lt;/tt&amp;gt; , which removes the last element from an array and returns it.&lt;br /&gt;
&lt;br /&gt;
So far, we've placed integers and strings only inside arrays. However, PHP allows you to assign any data type you want to an array element: booleans, integers, floating-point numbers, strings, objects, resources, &amp;lt;tt&amp;gt;NULL&amp;lt;/tt&amp;gt;, and even other arrays. So, you can pull arrays or objects directly from a database and place them into an array:&lt;br /&gt;
&lt;br /&gt;
 while ($row = mysql_fetch_row($r)) {&lt;br /&gt;
     $fruits[ ] = $row;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 while ($obj = mysql_fetch_object($s)) {&lt;br /&gt;
     $vegetables[ ] = $obj;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The first &amp;lt;tt&amp;gt;while&amp;lt;/tt&amp;gt; statement creates an array of arrays; the second creates an array of objects. See [[PHP Cookbook/Arrays#Storing Multiple Elements per Key in an Array|Recipe 4.3]] for more on storing multiple elements per key.&lt;br /&gt;
&lt;br /&gt;
To define an array not using integer keys but string keys, you can also use &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt;, but specify the key/value pairs with &amp;lt;tt&amp;gt;=&amp;gt;&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $fruits = array('red' =&amp;gt; 'Apples', 'yellow' =&amp;gt; 'Bananas', &lt;br /&gt;
                 'beige' =&amp;gt; 'Cantaloupes', 'brown' =&amp;gt; 'Dates');&lt;br /&gt;
&lt;br /&gt;
Now, the value of &amp;lt;tt&amp;gt;$fruits['beige']&amp;lt;/tt&amp;gt; is &amp;lt;tt&amp;gt;'Cantaloupes'&amp;lt;/tt&amp;gt;. This is shorthand for:&lt;br /&gt;
&lt;br /&gt;
 $fruits['red'] = 'Apples';&lt;br /&gt;
 $fruits['yellow'] = 'Bananas';&lt;br /&gt;
 $fruits['beige'] = 'Cantaloupes';&lt;br /&gt;
 $fruits['brown'] = 'Dates';&lt;br /&gt;
&lt;br /&gt;
Each array can only hold one unique value for each key. Adding:&lt;br /&gt;
&lt;br /&gt;
 $fruits['red'] = 'Strawberry';&lt;br /&gt;
&lt;br /&gt;
overwrites the value of &amp;lt;tt&amp;gt;'Apples'&amp;lt;/tt&amp;gt;. However, you can always add another key at a later time:&lt;br /&gt;
&lt;br /&gt;
 $fruits['orange'] = 'Orange';&lt;br /&gt;
&lt;br /&gt;
The more you program in PHP, the more you find yourself using associative arrays instead of numerical ones. Instead of creating a numeric array with string values, you can create an associative array and place your values as its keys. If you want, you can then store additional information in the element's value. There's no speed penalty for doing this, and PHP preserves the ordering. Plus, looking up or changing a value is easy because you already know the key.&lt;br /&gt;
&lt;br /&gt;
The easiest way to cycle though an array and operate on all or some of the elements inside is to use &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $fruits = array('red' =&amp;gt; 'Apples', 'yellow' =&amp;gt; 'Bananas', &lt;br /&gt;
                 'beige' =&amp;gt; 'Cantaloupes', 'brown' =&amp;gt; 'Dates');&lt;br /&gt;
 &lt;br /&gt;
 foreach ($fruits as $color =&amp;gt; $fruit) {&lt;br /&gt;
     print &amp;quot;$fruit are $color.\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
 '''Apples are red.'''&lt;br /&gt;
             '''Bananas are yellow.'''&lt;br /&gt;
             '''Cantaloupes are beige.'''&lt;br /&gt;
             '''Dates are brown.'''&lt;br /&gt;
          &lt;br /&gt;
&lt;br /&gt;
Each time through the loop, PHP assigns the next key to &amp;lt;tt&amp;gt;$color&amp;lt;/tt&amp;gt; and the key's value to &amp;lt;tt&amp;gt;$fruit&amp;lt;/tt&amp;gt;. When there are no elements left in the array, the loop finishes.&lt;br /&gt;
&lt;br /&gt;
To break an array apart into individual variables, use &amp;lt;tt&amp;gt;list( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');&lt;br /&gt;
 &lt;br /&gt;
 list($red, $yellow, $beige, $brown) = $fruits;&lt;br /&gt;
&lt;br /&gt;
== Specifying an Array Not Beginning at Element 0 ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to assign multiple elements to an array in one step, but you don't want the first index to be 0.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Instruct &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; to use a different index using the &amp;lt;tt&amp;gt;=&amp;gt;&amp;lt;/tt&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
 $presidents = array(1 =&amp;gt; 'Washington', 'Adams', 'Jefferson', 'Madison');&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Arrays in PHP, like most, but not all, computer languages begin with the first entry located at index 0. Sometimes, however, the data you're storing makes more sense if the list begins at 1. (And we're not just talking to recovering Pascal programmers here.)&lt;br /&gt;
&lt;br /&gt;
In the Solution, George Washington is the first president, not the zeroth, so if you wish to print a list of the presidents, it's simpler to do this:&lt;br /&gt;
&lt;br /&gt;
 foreach ($presidents as $number =&amp;gt; $president) {&lt;br /&gt;
     print &amp;quot;$number: $president\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
than this:&lt;br /&gt;
&lt;br /&gt;
 foreach ($presidents as $number =&amp;gt; $president) {&lt;br /&gt;
     $number++;&lt;br /&gt;
     print &amp;quot;$number: $president\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The feature isn't restricted to the number 1; any integer works:&lt;br /&gt;
&lt;br /&gt;
 $reconstruction_presidents = array(16 =&amp;gt; 'Lincoln', 'Johnson', 'Grant');&lt;br /&gt;
&lt;br /&gt;
Also, you can use &amp;lt;tt&amp;gt;=&amp;gt;&amp;lt;/tt&amp;gt; multiple times in one call:&amp;lt;ref&amp;gt;John Tyler was elected as Harrison's Vice President under the Whig Party platform but was expelled from the party shortly after assuming the presidency following the death of Harrison.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 $whig_presidents = array(9 =&amp;gt; 'Harrison', 'Tyler', 12 =&amp;gt; 'Taylor', 'Fillmore');&lt;br /&gt;
&lt;br /&gt;
PHP even allows you to use negative numbers in the &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; call. (In fact, this method works for noninteger keys, too.) What you'll get is technically an associative array, although as we said, the line between numeric arrays and associative arrays is often blurred in PHP; this is just another one of these cases.&lt;br /&gt;
&lt;br /&gt;
 $us_leaders = array(-1 =&amp;gt; 'George II', 'George III', 'Washington');&lt;br /&gt;
&lt;br /&gt;
If Washington is the first U.S. leader, George III is the zeroth, and his grandfather George II is the negative-first.&lt;br /&gt;
&lt;br /&gt;
Of course, you can mix and match numeric and string keys in one &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; definition, but it's confusing and very rarely needed:&lt;br /&gt;
&lt;br /&gt;
 $presidents = array(1 =&amp;gt; 'Washington', 'Adams', 'Honest' =&amp;gt; 'Lincoln', 'Jefferson');&lt;br /&gt;
&lt;br /&gt;
This is equivalent to:&lt;br /&gt;
&lt;br /&gt;
 $presidents[1]        = 'Washington';   // Key is 1&lt;br /&gt;
 $presidents[ ]         = 'Adams';        // Key is 1 + 1 =&amp;gt; 2&lt;br /&gt;
 $presidents['Honest'] = 'Lincoln';      // Key is 'Honest'&lt;br /&gt;
 $presidents[ ]         = 'Jefferson';    // Key is 2 + 1 =&amp;gt; 3&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array''.&lt;br /&gt;
&lt;br /&gt;
== Storing Multiple Elements per Key in an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to associate multiple elements with a single key.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Store the multiple elements in an array:&lt;br /&gt;
&lt;br /&gt;
 $fruits = array('red' =&amp;gt; array('strawberry','apple'),&lt;br /&gt;
                 'yellow' =&amp;gt; array('banana'));&lt;br /&gt;
&lt;br /&gt;
Or, use an object:&lt;br /&gt;
&lt;br /&gt;
 while ($obj = mysql_fetch_object($r)) {&lt;br /&gt;
     $fruits[ ] = $obj;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
In PHP, keys are unique per array, so you can't associate more than one entry in a key without overwriting the old value. Instead, store your values in an anonymous array:&lt;br /&gt;
&lt;br /&gt;
 $fruits['red'][ ] = 'strawberry';&lt;br /&gt;
 $fruits['red'][ ] = 'apple';&lt;br /&gt;
 $fruits['yellow'][ ] = 'banana';&lt;br /&gt;
&lt;br /&gt;
Or, if you're processing items in a loop:&lt;br /&gt;
&lt;br /&gt;
 while (list($color,$fruit) = mysql_fetch_array($r)) {&lt;br /&gt;
     $fruits[$color][ ] = $fruit;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
To print the entries, loop through the array:&lt;br /&gt;
&lt;br /&gt;
 foreach ($fruits as $color=&amp;gt;$color_fruit) {&lt;br /&gt;
     // $color_fruit is an array&lt;br /&gt;
     foreach ($color_fruit as $fruit) {&lt;br /&gt;
         print &amp;quot;$fruit is colored $color.&amp;amp;lt;br&amp;gt;&amp;quot;;&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Or use the &amp;lt;tt&amp;gt;pc_array_to_comma_string( )&amp;lt;/tt&amp;gt; function from [[PHP Cookbook/Arrays#Printing an Array with Commas|Recipe 4.10]].&lt;br /&gt;
&lt;br /&gt;
 foreach ($fruits as $color=&amp;gt;$color_fruit) {&lt;br /&gt;
     print &amp;quot;$color colored fruits include &amp;quot; . &lt;br /&gt;
         pc_array_to_comma_string($color_fruit) . &amp;quot;&amp;amp;lt;br&amp;gt;&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Printing an Array with Commas|Recipe 4.10]] for how to print arrays with commas.&lt;br /&gt;
&lt;br /&gt;
== Initializing an Array to a Range of Integers ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to assign a series of consecutive integers to an array.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;range($start, $stop)&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $cards = range(1, 52);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
For increments other than 1, you can use:&lt;br /&gt;
&lt;br /&gt;
 function pc_array_range($start, $stop, $step) {&lt;br /&gt;
     $array = array();&lt;br /&gt;
     for ($i = $start; $i &amp;lt;= $stop; $i += $step) {&lt;br /&gt;
         $array[] = $i;&lt;br /&gt;
     }&lt;br /&gt;
     return $array;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
So, for odd numbers:&lt;br /&gt;
&lt;br /&gt;
 $odd = pc_array_range(1, 52, 2);&lt;br /&gt;
&lt;br /&gt;
And, for even numbers:&lt;br /&gt;
&lt;br /&gt;
 $even = pc_array_range(2, 52, 2);&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Numbers#Operating on a Series of Integers|Recipe 2.5]] for how to operate on a series of integers; documentation on &amp;lt;tt&amp;gt;range( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/range''.&lt;br /&gt;
&lt;br /&gt;
== Iterating Through an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to cycle though an array and operate on all or some of the elements inside.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 foreach ($array as $value) {&lt;br /&gt;
     // Act on $value&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Or, to get an array's keys and values:&lt;br /&gt;
&lt;br /&gt;
 foreach ($array as $key =&amp;gt; $value) {&lt;br /&gt;
     // Act II&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Another technique is to use &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 for ($key = 0, $size = count($array); $key &amp;lt; $size; $key++) {&lt;br /&gt;
    // Act III&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Finally, you can use &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; in combination with &amp;lt;tt&amp;gt;list( )&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;while&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 reset($array) // reset internal pointer to beginning of array&lt;br /&gt;
 while (list($key, $value) = each ($array)) {&lt;br /&gt;
     // Final Act&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loop is the shortest way to iterate through an array:&lt;br /&gt;
&lt;br /&gt;
 // foreach with values&lt;br /&gt;
 foreach ($items as $cost) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 // foreach with keys and values&lt;br /&gt;
 foreach($items as $item =&amp;gt; $cost) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
With &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;, PHP iterates over a copy of the array instead of the actual array. In contrast, when using &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt;, PHP iterates over the original array. So, if you modify the array inside the loop, you may (or may not) get the behavior you expect.&lt;br /&gt;
&lt;br /&gt;
If you want to modify the array, reference it directly:&lt;br /&gt;
&lt;br /&gt;
 reset($items);&lt;br /&gt;
 while (list($item, $cost) = each($items)) {&lt;br /&gt;
     if (! in_stock($item)) { &lt;br /&gt;
         unset($items[$item]);           // address the array directly&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The variables returned by &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; aren't aliases for the original values in the array: they're copies, so, if you modify them, it's not reflected in the array. That's why you need to modify &amp;lt;tt&amp;gt;$items[$item]&amp;lt;/tt&amp;gt; instead of &amp;lt;tt&amp;gt;$item&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
When using &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt;, PHP keeps track of where you are inside the loop. After completing a first pass through, to begin again at the start, call &amp;lt;tt&amp;gt;reset( )&amp;lt;/tt&amp;gt; to move the pointer back to the front of the array. Otherwise, &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; returns &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; loop works only for arrays with consecutive integer keys. Unless you're modifying the size of your array, it's inefficient to recompute the &amp;lt;tt&amp;gt;count( )&amp;lt;/tt&amp;gt; of &amp;lt;tt&amp;gt;$items&amp;lt;/tt&amp;gt; each time through the loop, so we always use a &amp;lt;tt&amp;gt;$size&amp;lt;/tt&amp;gt; variable to hold the array's size:&lt;br /&gt;
&lt;br /&gt;
 for ($item = 0, $size = count($items); $item &amp;lt; $size; $item++) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
If you prefer to count efficiently with one variable, count backwards:&lt;br /&gt;
&lt;br /&gt;
 for ($item = count($items) - 1; $item &amp;gt;= 0; $item--) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The associative version of the &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; loop is:&lt;br /&gt;
&lt;br /&gt;
 for (reset($array); $key = key($array); next($array) ) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
This fails if any element holds a string that evaluates to &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt;, so a perfectly normal value such as 0 causes the loop to end early.&lt;br /&gt;
&lt;br /&gt;
Finally, use &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt; to hand off each element to a function for processing:&lt;br /&gt;
&lt;br /&gt;
 // lowercase all words&lt;br /&gt;
 $lc = array_map('strtolower', $words);&lt;br /&gt;
&lt;br /&gt;
The first argument to &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt; is a function to modify an individual element, and the second is the array to be iterated through.&lt;br /&gt;
&lt;br /&gt;
Generally, we find these functions less flexible than the previous methods, but they are well-suited for the processing and merging of multiple arrays.&lt;br /&gt;
&lt;br /&gt;
If you're unsure if the data you'll be processing is a scalar or an array, you need to protect against calling &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; with a non-array. One method is to use &amp;lt;tt&amp;gt;is_array( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 if (is_array($items)) {&lt;br /&gt;
     // foreach loop code for array&lt;br /&gt;
 } else {&lt;br /&gt;
     // code for scalar&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Another method is to coerce all variables into array form using &amp;lt;tt&amp;gt;settype( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 settype($items, 'array');&lt;br /&gt;
 // loop code for arrays&lt;br /&gt;
&lt;br /&gt;
This turns a scalar value into a one element array and cleans up your code at the expense of a little overhead.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; at ''http://www.php.net/for'', &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; at ''http://www.php.net/foreach'', &amp;lt;tt&amp;gt;while&amp;lt;/tt&amp;gt; at ''http://www.php.net/while'', &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/each'', &amp;lt;tt&amp;gt;reset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/reset'', and &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-map''.&lt;br /&gt;
&lt;br /&gt;
== Deleting Elements from an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to remove one or more elements from an array.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
To delete one element, use &amp;lt;tt&amp;gt;unset( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 unset($array[3]);&lt;br /&gt;
 unset($array['foo']);&lt;br /&gt;
&lt;br /&gt;
To delete multiple noncontiguous elements, also use &amp;lt;tt&amp;gt;unset( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 unset($array[3], $array[5]);&lt;br /&gt;
 unset($array['foo'], $array['bar']);&lt;br /&gt;
&lt;br /&gt;
To delete multiple contiguous elements, use &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 array_splice($array, $offset, $length);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;$array[3] = $array['foo'] = '';&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Besides syntax, there's a logical difference between using &amp;lt;tt&amp;gt;unset( )&amp;lt;/tt&amp;gt; and assigning &amp;lt;tt&amp;gt;&amp;lt;nowiki&amp;gt;''&amp;lt;/nowiki&amp;gt;&amp;lt;/tt&amp;gt; to the element. The first says &amp;quot;This doesn't exist anymore,&amp;quot; while the second says &amp;quot;This still exists, but its value is the empty string.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
If you're dealing with numbers, assigning &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:&lt;br /&gt;
&lt;br /&gt;
 unset($products['XL1000']);&lt;br /&gt;
&lt;br /&gt;
However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:&lt;br /&gt;
&lt;br /&gt;
 $products['XL1000'] = 0;&lt;br /&gt;
&lt;br /&gt;
If you &amp;lt;tt&amp;gt;unset( )&amp;lt;/tt&amp;gt; an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;// create a &amp;quot;numeric&amp;quot; array&lt;br /&gt;
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');&lt;br /&gt;
print $animals[1];  // prints 'bee'&lt;br /&gt;
print $animals[2];  // prints 'cat'&lt;br /&gt;
count($animals);    // returns 6&lt;br /&gt;
&lt;br /&gt;
// unset( )&lt;br /&gt;
unset($animals[1]); // removes element $animals[1] = 'bee'&lt;br /&gt;
print $animals[1];  // prints '' and throws an E_NOTICE error&lt;br /&gt;
print $animals[2];  // still prints 'cat'&lt;br /&gt;
count($animals);    // returns 5, even though $array[5] is 'fox'&lt;br /&gt;
&lt;br /&gt;
// add new element&lt;br /&gt;
$animals[ ] = 'gnu'; // add new element (not Unix)&lt;br /&gt;
print $animals[1];  // prints '', still empty&lt;br /&gt;
print $animals[6];  // prints 'gnu', this is where 'gnu' ended up&lt;br /&gt;
count($animals);    // returns 6 &lt;br /&gt;
&lt;br /&gt;
// assign ''&lt;br /&gt;
$animals[2] = '';   // zero out value&lt;br /&gt;
print $animals[2];  // prints ''&lt;br /&gt;
count($animals);    // returns 6, count does not decrease&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To compact the array into a densely filled numeric array, use &amp;lt;tt&amp;gt;array_values( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $animals = array_values($animals);&lt;br /&gt;
&lt;br /&gt;
Alternatively, &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt; automatically reindexes arrays to avoid leaving holes:&lt;br /&gt;
&lt;br /&gt;
 // create a &amp;quot;numeric&amp;quot; array&lt;br /&gt;
 $animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');&lt;br /&gt;
 array_splice($animals, 2, 2);&lt;br /&gt;
 print_r($animals);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; ant'''&lt;br /&gt;
                '''    [1] =&amp;gt; bee'''&lt;br /&gt;
                '''    [2] =&amp;gt; elk'''&lt;br /&gt;
                '''    [3] =&amp;gt; fox'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use &amp;lt;tt&amp;gt;array_shift( )&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;array_pop( )&amp;lt;/tt&amp;gt;, respectively.&lt;br /&gt;
&lt;br /&gt;
However, if you find yourself often running into problems because of holes in arrays, you may not be &amp;quot;thinking PHP.&amp;quot; Look at the ways to iterate through the array in [[PHP Cookbook/Arrays#Iterating Through an Array|Recipe 4.5]] that don't involve using a &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; loop.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Iterating Through an Array|Recipe 4.5]] for iteration techniques; documentation on &amp;lt;tt&amp;gt;unset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/unset'', &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-splice'', and &amp;lt;tt&amp;gt;array_values( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-values''.&lt;br /&gt;
&lt;br /&gt;
== Changing Array Size ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to modify the size of an array, either by making it larger or smaller than its current size.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt; to make an array grow:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;// start at three&lt;br /&gt;
$array = array('apple', 'banana', 'coconut');&lt;br /&gt;
&lt;br /&gt;
// grow to five&lt;br /&gt;
$array = array_pad($array, 5, '');&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, &amp;lt;tt&amp;gt;count($array)&amp;lt;/tt&amp;gt; is &amp;lt;tt&amp;gt;5&amp;lt;/tt&amp;gt;, and the last two elements contain the empty string.&lt;br /&gt;
&lt;br /&gt;
To reduce an array, you can use &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 // no assignment to $array&lt;br /&gt;
 array_splice($array, 2);&lt;br /&gt;
&lt;br /&gt;
This removes all but the first two elements from &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Arrays aren't a predeclared size in PHP, so you can resize them on the fly.&lt;br /&gt;
&lt;br /&gt;
To pad an array, use &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt;. The first argument is the array to be padded. The next argument is the size and direction you want to pad. To pad to the right, use a positive integer; to pad to the left, use a negative one. The third argument is the value to be assigned to the newly created entries. The function returns a modified array and doesn't alter the original.&lt;br /&gt;
&lt;br /&gt;
Here are some examples:&lt;br /&gt;
&lt;br /&gt;
 // make a four-element array with 'dates' to the right&lt;br /&gt;
 $array = array('apple', 'banana', 'coconut');&lt;br /&gt;
 $array = array_pad($array, 4, 'dates');&lt;br /&gt;
 print_r($array);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; apple'''&lt;br /&gt;
                '''    [1] =&amp;gt; banana'''&lt;br /&gt;
                '''    [2] =&amp;gt; coconut'''&lt;br /&gt;
                '''    [3] =&amp;gt; dates'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
 &lt;br /&gt;
 // make a six-element array with 'zucchinis' to the left&lt;br /&gt;
 $array = array_pad($array, -6, 'zucchini');&lt;br /&gt;
 print_r($array);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; zucchini'''&lt;br /&gt;
                '''    [1] =&amp;gt; zucchini'''&lt;br /&gt;
                '''    [2] =&amp;gt; apple'''&lt;br /&gt;
                '''    [3] =&amp;gt; banana'''&lt;br /&gt;
                '''    [4] =&amp;gt; coconut'''&lt;br /&gt;
                '''    [5] =&amp;gt; dates'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
Be careful. &amp;lt;tt&amp;gt;array_pad($array, 4, 'dates')&amp;lt;/tt&amp;gt; makes sure an &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt; is ''at least'' four elements long, it doesn't add four ''new'' elements. In this case, if &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt; was already four elements or larger, &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt; would return an unaltered &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Also, if you declare a value for a fourth element, &amp;lt;tt&amp;gt;$array[4]&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $array = array('apple', 'banana', 'coconut');&lt;br /&gt;
 $array[4] = 'dates';&lt;br /&gt;
&lt;br /&gt;
you end up with a four-element array with indexes &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;1&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;2&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;4&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 Array&lt;br /&gt;
 (&lt;br /&gt;
     [0] =&amp;gt; apple&lt;br /&gt;
     [1] =&amp;gt; banana&lt;br /&gt;
     [2] =&amp;gt; coconut&lt;br /&gt;
     [4] =&amp;gt; dates&lt;br /&gt;
 )&lt;br /&gt;
&lt;br /&gt;
PHP essentially turns this into an associative array that happens to have integer keys.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt; function, unlike &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt;, has the side-effect of modifying the original array. It returns the spliced out array. That's why you don't assign the return value to &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt;. However, like &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt;, you can splice from either the right or left. So, calling &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt; with a value of &amp;lt;tt&amp;gt;-2&amp;lt;/tt&amp;gt; chops off the last two elements from the end:&lt;br /&gt;
&lt;br /&gt;
 // make a four-element array&lt;br /&gt;
 $array = array('apple', 'banana', 'coconut', 'dates');&lt;br /&gt;
 &lt;br /&gt;
 // shrink to three elements&lt;br /&gt;
 array_splice($array, 3);&lt;br /&gt;
 &lt;br /&gt;
 // remove last element, equivalent to array_pop( )&lt;br /&gt;
 array_splice($array, -1);&lt;br /&gt;
 &lt;br /&gt;
 // only remaining fruits are apple and banana&lt;br /&gt;
 print_r($array);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; apple'''&lt;br /&gt;
                '''    [1] =&amp;gt; banana'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_pad( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-pad'' and &amp;lt;tt&amp;gt;array_splice( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-splice''.&lt;br /&gt;
&lt;br /&gt;
== Appending One Array to Another ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to combine two arrays into one.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $garden = array_merge($fruits, $vegetables);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt; function works with both predefined arrays and arrays defined in place using &amp;lt;tt&amp;gt;array( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $p_languages = array('Perl', 'PHP');&lt;br /&gt;
 $p_languages = array_merge($p_languages, array('Python'));&lt;br /&gt;
 print_r($p_languages);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; PHP'''&lt;br /&gt;
                '''    [1] =&amp;gt; Perl'''&lt;br /&gt;
                '''    [2] =&amp;gt; Python'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
Accordingly, merged arrays can be either preexisting arrays, as with &amp;lt;tt&amp;gt;$p_languages&amp;lt;/tt&amp;gt;, or anonymous arrays, as with &amp;lt;tt&amp;gt;array('Python')&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
You can't use &amp;lt;tt&amp;gt;array_push( )&amp;lt;/tt&amp;gt; , because PHP won't automatically flatten out the array into series of independent variables, and you'll end up with a nested array. Thus:&lt;br /&gt;
&lt;br /&gt;
 array_push($p_languages, array('Python'));&lt;br /&gt;
 print_r($p_languages);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; PHP'''&lt;br /&gt;
                '''    [1] =&amp;gt; Perl'''&lt;br /&gt;
                '''    [2] =&amp;gt; Array'''&lt;br /&gt;
                '''        ('''&lt;br /&gt;
                '''            [0] =&amp;gt; Python'''&lt;br /&gt;
                '''        )'''&lt;br /&gt;
 &lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
Merging arrays with only numerical keys causes the arrays to get renumbered, so values aren't lost. Merging arrays with string keys causes the second array to overwrite the value of any duplicated keys. Arrays with both types of keys exhibit both types of behavior. For example:&lt;br /&gt;
&lt;br /&gt;
 $lc = array('a', 'b' =&amp;gt; 'b'); // lower-case letters as values&lt;br /&gt;
 $uc = array('A', 'b' =&amp;gt; 'B'); // upper-case letters as values&lt;br /&gt;
 $ac = array_merge($lc, $uc);  // all-cases?&lt;br /&gt;
 print_r($ac);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; a'''&lt;br /&gt;
                '''    [b] =&amp;gt; B'''&lt;br /&gt;
                '''    [1] =&amp;gt; A'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
The uppercase A has been renumbered from index 0 to index 1, to avoid a collision, and merged onto the end. The uppercase B has overwritten the lowercase b and replaced it in the original place within the array.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;+&amp;lt;/tt&amp;gt; operator can also merge arrays. The array on the right overwrites any identically named keys found on the left. It doesn't do any reordering to prevent collisions. Using the previous example:&lt;br /&gt;
&lt;br /&gt;
 print_r($a + $b);&lt;br /&gt;
 print_r($b + $a);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; a'''&lt;br /&gt;
                '''    [b] =&amp;gt; b'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
                '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; A'''&lt;br /&gt;
                '''    [b] =&amp;gt; B'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
Since &amp;lt;tt&amp;gt;a&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;A&amp;lt;/tt&amp;gt; both have a key of &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;b&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;B&amp;lt;/tt&amp;gt; both have a key of &amp;lt;tt&amp;gt;b&amp;lt;/tt&amp;gt;, you end up with a total of only two elements in the merged arrays.&lt;br /&gt;
&lt;br /&gt;
In the first case, &amp;lt;tt&amp;gt;$a + $b&amp;lt;/tt&amp;gt; becomes just &amp;lt;tt&amp;gt;$b&amp;lt;/tt&amp;gt;, and in the other, &amp;lt;tt&amp;gt;$b + $a&amp;lt;/tt&amp;gt; becomes &amp;lt;tt&amp;gt;$a&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
However, if you had two distinctly keyed arrays, this wouldn't be a problem, and the new array would be the union of the two arrays.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-merge''.&lt;br /&gt;
&lt;br /&gt;
== Turning an Array into a String ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You have an array, and you want to convert it into a nicely formatted string.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 // make a comma delimited list&lt;br /&gt;
 $string = join(',', $array);&lt;br /&gt;
&lt;br /&gt;
Or loop yourself:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;$string = '';&lt;br /&gt;
&lt;br /&gt;
foreach ($array as $key =&amp;gt; $value) {&lt;br /&gt;
    $string .= &amp;quot;,$value&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$string = substr($string, 1); // remove leading &amp;quot;,&amp;quot;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
If you can use &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; , do; it's faster than any PHP-based loop. However, &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; isn't very flexible. First, it places a delimiter only between elements, not around them. To wrap elements inside HTML bold tags and separate them with commas, do this:&lt;br /&gt;
&lt;br /&gt;
 $left  = '&amp;amp;lt;b&amp;gt;';&lt;br /&gt;
 $right = '&amp;amp;lt;/b&amp;gt;';&lt;br /&gt;
 &lt;br /&gt;
 $html = $left . join(&amp;quot;$right,$left&amp;quot;, $html) . $right;&lt;br /&gt;
&lt;br /&gt;
Second, &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; doesn't allow you to discriminate against values. If you want to include a subset of entries, you need to loop yourself:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;$string = '';&lt;br /&gt;
&lt;br /&gt;
foreach ($fields as $key =&amp;gt; $value) {&lt;br /&gt;
    // don't include password&lt;br /&gt;
    if ('password' != $key) {&lt;br /&gt;
        $string .= &amp;quot;,&amp;lt;b&amp;gt;$value&amp;lt;/b&amp;gt;&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$string = substr($string, 1); // remove leading &amp;quot;,&amp;quot;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that a separator is always added to each value, then stripped off outside the loop. While it's somewhat wasteful to add something that will be later subtracted, it's far cleaner and efficient (in most cases) then attempting to embed logic inside of the loop. To wit:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;$string = '';&lt;br /&gt;
foreach ($fields as $key =&amp;gt; $value) {&lt;br /&gt;
    // don't include password&lt;br /&gt;
    if ('password' != $value) {&lt;br /&gt;
        if (!empty($string)) { $string .= ','; }&lt;br /&gt;
        $string .= &amp;quot;&amp;lt;b&amp;gt;$value&amp;lt;/b&amp;gt;&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now you have to check &amp;lt;tt&amp;gt;$string&amp;lt;/tt&amp;gt; every time you append a value. That's worse than the simple &amp;lt;tt&amp;gt;substr( )&amp;lt;/tt&amp;gt; call. Also, prepend the delimiter (in this case a comma) instead of appending it because it's faster to shorten a string from the front than the rear.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Printing an Array with Commas|Recipe 4.10]] for printing an array with commas; documentation on &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/join'' and &amp;lt;tt&amp;gt;substr( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/substr''.&lt;br /&gt;
&lt;br /&gt;
== Printing an Array with Commas ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to print out an array with commas separating the elements and with an &amp;quot;and&amp;quot; before the last element if there are more than two elements in the array.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use the &amp;lt;tt&amp;gt;pc_array_to_comma_string( )&amp;lt;/tt&amp;gt; function shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-1|Example 4-1]], which returns the correct string.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-1&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-1. pc_array_to_comma_string( )'''&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;function pc_array_to_comma_string($array) {&lt;br /&gt;
&lt;br /&gt;
    switch (count($array)) {&lt;br /&gt;
    case 0:&lt;br /&gt;
        return '';&lt;br /&gt;
&lt;br /&gt;
    case 1:&lt;br /&gt;
        return reset($array);&lt;br /&gt;
    &lt;br /&gt;
    case 2:&lt;br /&gt;
        return join(' and ', $array);&lt;br /&gt;
&lt;br /&gt;
    default:&lt;br /&gt;
        $last = array_pop($array);&lt;br /&gt;
        return join(', ', $array) . &amp;quot;, and $last&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
If you have a list of items to print, it's useful to print them in a grammatically correct fashion. It looks awkward to display text like this:&lt;br /&gt;
&lt;br /&gt;
 $thundercats = array('Lion-O', 'Panthro', 'Tygra', 'Cheetara', 'Snarf');&lt;br /&gt;
 print 'ThunderCat good guys include ' . join(', ', $thundercats) . '.';&lt;br /&gt;
 '''ThunderCat good guys include Lion-O, Panthro, Tygra, Cheetara, Snarf'''.&lt;br /&gt;
&lt;br /&gt;
This implementation of this function isn't completely straightforward, since we want &amp;lt;tt&amp;gt;pc_array_to_comma_string( )&amp;lt;/tt&amp;gt; to work with all arrays, not just numeric ones beginning at &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;. If restricted only to that subset, for an array of size one, you return &amp;lt;tt&amp;gt;$array[0]&amp;lt;/tt&amp;gt;. But, if the array doesn't begin at &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;$array[0]&amp;lt;/tt&amp;gt; is empty. So, you can use the fact that &amp;lt;tt&amp;gt;reset( )&amp;lt;/tt&amp;gt; , which resets an array's internal pointer, also returns the value of the first array element.&lt;br /&gt;
&lt;br /&gt;
For similar reasons, you call &amp;lt;tt&amp;gt;array_pop( )&amp;lt;/tt&amp;gt; to grab the end element, instead of assuming it's located at &amp;lt;tt&amp;gt;$array[count($array)-1]&amp;lt;/tt&amp;gt;. This allows you to use &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; on &amp;lt;tt&amp;gt;$array&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Also note that the code for case 2 actually also works correctly for case 1. And, the default code works (though inefficiently) for case 2; however, the transitive property doesn't apply, so you can't use the default code on elements of size 1.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Turning an Array into a String|Recipe 4.9]] for turning an array into a string; documentation on &amp;lt;tt&amp;gt;join( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/join'', &amp;lt;tt&amp;gt;array_pop( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-pop'', and &amp;lt;tt&amp;gt;reset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/reset''.&lt;br /&gt;
&lt;br /&gt;
== Checking if a Key Is in an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to know if an array contains a certain key.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;isset( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 if (isset($array['key'])) { /* there is a value for 'key' in $array */ }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
You can check the definedness of an array element just as you'd for any other variable. See the Introduction to [[PHP Cookbook/Variables|Chapter 5]] for more information about the truth value of variables.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;isset( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/isset''.&lt;br /&gt;
&lt;br /&gt;
== Checking if an Element Is in an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to know if an array contains a certain value.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 if (in_array($value, $array)) {&lt;br /&gt;
     // an element has $value as its value in array $array&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; to check if an element of an array holds a value:&lt;br /&gt;
&lt;br /&gt;
 $book_collection = array('Emma', 'Pride and Prejudice', 'Northhanger Abbey');&lt;br /&gt;
 $book = 'Sense and Sensibility';&lt;br /&gt;
 &lt;br /&gt;
 if (in_array($book, $book_collection) { &lt;br /&gt;
     echo 'Own it.';&lt;br /&gt;
 } else {&lt;br /&gt;
     echo 'Need it.';&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The default behavior of &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; is to compare items using the &amp;lt;tt&amp;gt;==&amp;lt;/tt&amp;gt; operator. To use the strict equality check, &amp;lt;tt&amp;gt;===&amp;lt;/tt&amp;gt;, pass &amp;lt;tt&amp;gt;true&amp;lt;/tt&amp;gt; as the third parameter to &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $array = array(1, '2', 'three');&lt;br /&gt;
 &lt;br /&gt;
 in_array(0, $array);        // true!&lt;br /&gt;
 in_array(0, $array, true);  // false&lt;br /&gt;
 in_array(1, $array);        // true&lt;br /&gt;
 in_array(1, $array, true);  // true&lt;br /&gt;
 in_array(2, $array);        // true&lt;br /&gt;
 in_array(2, $array, true);  // false&lt;br /&gt;
&lt;br /&gt;
The first check, &amp;lt;tt&amp;gt;in_array(0, $array)&amp;lt;/tt&amp;gt;, evaluates to &amp;lt;tt&amp;gt;true&amp;lt;/tt&amp;gt; because to compare the number &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; against the string &amp;lt;tt&amp;gt;three&amp;lt;/tt&amp;gt;, PHP casts &amp;lt;tt&amp;gt;three&amp;lt;/tt&amp;gt; to an integer. Since &amp;lt;tt&amp;gt;three&amp;lt;/tt&amp;gt; isn't a numeric string, as is &amp;lt;tt&amp;gt;2&amp;lt;/tt&amp;gt;, it becomes &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;. Therefore, &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; thinks there's a match.&lt;br /&gt;
&lt;br /&gt;
Consequently, when comparing numbers against data that may contain strings, it's safest to use a strict comparison.&lt;br /&gt;
&lt;br /&gt;
If you find yourself calling &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; multiple times on the same array, it may be better to use an associative array, with the original array elements as the keys in the new associative array. Looking up entries using &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; takes linear time; with an associative array, it takes constant time.&lt;br /&gt;
&lt;br /&gt;
If you can't create the associative array directly but need to convert from a traditional one with integer keys, use &amp;lt;tt&amp;gt;array_flip( )&amp;lt;/tt&amp;gt; to swap the keys and values of an array:&lt;br /&gt;
&lt;br /&gt;
 $book_collection = array('Emma',&lt;br /&gt;
                          'Pride and Prejudice',&lt;br /&gt;
                          'Northhanger Abbey');&lt;br /&gt;
 &lt;br /&gt;
 // convert from numeric array to associative array&lt;br /&gt;
 $book_collection = array_flip($book_collection);&lt;br /&gt;
 $book = 'Sense and Sensibility';&lt;br /&gt;
 &lt;br /&gt;
 if (isset($book_collection[$book])) { &lt;br /&gt;
     echo 'Own it.';&lt;br /&gt;
 } else {&lt;br /&gt;
     echo 'Need it.';&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Note that doing this condenses multiple keys with the same value into one element in the flipped array.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Finding the Position of an Element in an Array|Recipe 4.13]] for determining the position of an element in an array; documentation on &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/in-array'' and &amp;lt;tt&amp;gt;array_flip( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-flip''.&lt;br /&gt;
&lt;br /&gt;
== Finding the Position of an Element in an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to know if an element is in an array, and, if it is, you want to know where it is located.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;array_search( )&amp;lt;/tt&amp;gt; . It returns the key of the found element or &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $position = array_search($value, $array);&lt;br /&gt;
 if ($position !== false) {&lt;br /&gt;
     // the element in position $position has $value as its value in array $array&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; to find if an array contains a value; use &amp;lt;tt&amp;gt;array_search( )&amp;lt;/tt&amp;gt; to discover where that value is located. However, because &amp;lt;tt&amp;gt;array_search( )&amp;lt;/tt&amp;gt; gracefully handles searches in which the value isn't found, it's better to use &amp;lt;tt&amp;gt;array_search( )&amp;lt;/tt&amp;gt; instead of &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt;. The speed difference is minute, and the extra information is potentially useful:&lt;br /&gt;
&lt;br /&gt;
 $favorite_foods = array(1 =&amp;gt; 'artichokes', 'bread', 'cauliflower', 'deviled eggs');&lt;br /&gt;
 $food = 'cauliflower';&lt;br /&gt;
 $position = array_search($food, $favorite_foods);&lt;br /&gt;
 &lt;br /&gt;
 if ($position !== false) {&lt;br /&gt;
     echo &amp;quot;My #$position favorite food is $food&amp;quot;;&lt;br /&gt;
 } else {&lt;br /&gt;
     echo &amp;quot;Blech! I hate $food!&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Use the &amp;lt;tt&amp;gt;!==&amp;lt;/tt&amp;gt; check against &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt; because if your string is found in the array at position &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;, the &amp;lt;tt&amp;gt;if&amp;lt;/tt&amp;gt; evaluates to a logical &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt;, which isn't what is meant or wanted.&lt;br /&gt;
&lt;br /&gt;
If a value is in the array multiple times, &amp;lt;tt&amp;gt;array_search()&amp;lt;/tt&amp;gt; is only guaranteed to return one of the instances, not the first instance.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Checking if an Element Is in an Array|Recipe 4.12]] for checking whether an element is in an array; documentation on &amp;lt;tt&amp;gt;array_search( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-search''; for more sophisticated searching of arrays using regular expression, see &amp;lt;tt&amp;gt;preg_replace( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/preg-replace'' and [[PHP Cookbook/Regular Expressions|Chapter 13]].&lt;br /&gt;
&lt;br /&gt;
== Finding Elements That Pass a Certain Test ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to locate entries in an array that meet certain requirements.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use a &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loop:&lt;br /&gt;
&lt;br /&gt;
 $movies = array(...);&lt;br /&gt;
 &lt;br /&gt;
 foreach ($movies as $movie) {&lt;br /&gt;
     if ($movie['box_office_gross'] &amp;lt; 5000000) { $flops[] = $movie; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Or &amp;lt;tt&amp;gt;array_filter( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $movies = array(...);&lt;br /&gt;
 &lt;br /&gt;
 function flops($movie) {&lt;br /&gt;
     return ($movie['box_office_gross'] &amp;lt; 5000000) ? 1 : 0;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 $flops = array_filter($movies, 'flops');&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loops are simple; you scroll through the data and append elements to the return array that match your criteria.&lt;br /&gt;
&lt;br /&gt;
If you want only the first such element, exit the loop using &amp;lt;tt&amp;gt;break&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 foreach ($movies as $movie) {&lt;br /&gt;
     if ($movie['box_office_gross'] &amp;gt; 200000000) { $blockbuster = $movie; break; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
You can also return directly from a function:&lt;br /&gt;
&lt;br /&gt;
 function blockbuster($movies) {&lt;br /&gt;
     foreach ($movies as $movie) {&lt;br /&gt;
         if ($movie['box_office_gross'] &amp;gt; 200000000) { return $movie; }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
With &amp;lt;tt&amp;gt;array_filter( )&amp;lt;/tt&amp;gt; , however, you first create a callback function that returns &amp;lt;tt&amp;gt;true&amp;lt;/tt&amp;gt; for values you want to keep and &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt; for values you don't. Using &amp;lt;tt&amp;gt;array_filter( )&amp;lt;/tt&amp;gt;, you then instruct PHP to process the array as you do in the &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It's impossible to bail out early from &amp;lt;tt&amp;gt;array_filter( )&amp;lt;/tt&amp;gt;, so &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; provides more flexibility and is simpler to understand. Also, it's one of the few cases in which the built-in PHP function doesn't clearly outperform user-level code.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_filter( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-filter''.&lt;br /&gt;
&lt;br /&gt;
== Finding the Largest or Smallest Valued Element in an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You have an array of elements, and you want to find the largest or smallest valued element. For example, you want to find the appropriate scale when creating a histogram.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
To find the largest element, use &amp;lt;tt&amp;gt;max( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $largest = max($array);&lt;br /&gt;
&lt;br /&gt;
To find the smallest element, use &amp;lt;tt&amp;gt;min( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $smallest = min($array);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Normally, &amp;lt;tt&amp;gt;max( )&amp;lt;/tt&amp;gt; returns the larger of two elements, but if you pass it an array, it searches the entire array instead. Unfortunately, there's no way to find the index of the largest element using &amp;lt;tt&amp;gt;max( )&amp;lt;/tt&amp;gt;. To do that, you must sort the array in reverse order to put the largest element in position 0:&lt;br /&gt;
&lt;br /&gt;
 arsort($array);&lt;br /&gt;
&lt;br /&gt;
Now the value of the largest element is &amp;lt;tt&amp;gt;$array[0]&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you don't want to disturb the order of the original array, make a copy and sort the copy:&lt;br /&gt;
&lt;br /&gt;
 $copy = $array;&lt;br /&gt;
 arsort($copy);&lt;br /&gt;
&lt;br /&gt;
The same concept applies to &amp;lt;tt&amp;gt;min( )&amp;lt;/tt&amp;gt; but use &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; instead of &amp;lt;tt&amp;gt;arsort( )&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Sorting an Array|Recipe 4.17]] for sorting an array; documentation on &amp;lt;tt&amp;gt;max( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/max'', &amp;lt;tt&amp;gt;min( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/min'', &amp;lt;tt&amp;gt;arsort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/arsort'', and &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/min''.&lt;br /&gt;
&lt;br /&gt;
== Reversing an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to reverse the order of the elements in an array.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;array_reverse( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $array = array('Zero', 'One', 'Two');&lt;br /&gt;
 $reversed = array_reverse($array);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_reverse( )&amp;lt;/tt&amp;gt; function reverses the elements in an array. However, it's often possible to avoid this operation. If you wish to reverse an array you've just sorted, modify the sort to do the inverse. If you want to reverse a list you're about to loop through and process, just invert the loop. Instead of:&lt;br /&gt;
&lt;br /&gt;
 for ($i = 0, $size = count($array); $i &amp;lt; $size; $i++) {&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
do the following:&lt;br /&gt;
&lt;br /&gt;
 for ($i = count($array) - 1; $i &amp;gt;=0 ; $i--) { &lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, as always, use a &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; loop only on a tightly packed array.&lt;br /&gt;
&lt;br /&gt;
Another alternative would be, if possible, to invert the order elements are placed into the array. For instance, if you're populating an array from a series of rows returned from a database, you should be able to modify the query to &amp;lt;tt&amp;gt;ORDER DESC&amp;lt;/tt&amp;gt;. See your database manual for the exact syntax for your database.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_reverse( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-reverse''.&lt;br /&gt;
&lt;br /&gt;
== Sorting an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to sort an array in a specific way.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
To sort an array using the traditional definition of sort, use &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 $states = array('Delaware', 'Pennsylvania', 'New Jersey');&lt;br /&gt;
 sort($states);&lt;br /&gt;
&lt;br /&gt;
To sort numerically, pass &amp;lt;tt&amp;gt;SORT_NUMERIC&amp;lt;/tt&amp;gt; as the second argument to &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
 $scores = array(1, 10, 2, 20);&lt;br /&gt;
 sort($scores, SORT_NUMERIC);&lt;br /&gt;
&lt;br /&gt;
This resorts the numbers in ascending order &amp;lt;tt&amp;gt;(1, 2, 10, 20)&amp;lt;/tt&amp;gt; instead of lexicographical order &amp;lt;tt&amp;gt;(1, 10, 2, 20)&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt; function doesn't preserve the key/value association between elements; instead, entries are reindexed starting at &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; and going upward. (The one exception to this rule is a one-element array; its lone element doesn't have its index reset to &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt;. This is fixed as of PHP 4.2.3.)&lt;br /&gt;
&lt;br /&gt;
To preserve the key/value links, use &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt;. The &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; function is normally used for associative arrays, but it can also be useful when the indexes of the entries are meaningful:&lt;br /&gt;
&lt;br /&gt;
 $states = array(1 =&amp;gt; 'Delaware', 'Pennsylvania', 'New Jersey');&lt;br /&gt;
 asort($states);&lt;br /&gt;
 &lt;br /&gt;
 while (list($rank, $state) = each($states)) {&lt;br /&gt;
     print &amp;quot;$state was the #$rank state to join the United States\n&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;natsort( )&amp;lt;/tt&amp;gt; to sort the array using a natural sorting algorithm. Under natural sorting, you can mix strings and numbers inside your elements and still get the right answer.&lt;br /&gt;
&lt;br /&gt;
 $tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');&lt;br /&gt;
 natsort($tests);&lt;br /&gt;
&lt;br /&gt;
The elements are now ordered: &amp;lt;tt&amp;gt;'test1.php'&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;'test2.php'&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;'test10.php'&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;'test11.php'&amp;lt;/tt&amp;gt;. With natural sorting, the number &amp;lt;tt&amp;gt;10&amp;lt;/tt&amp;gt; comes after the number &amp;lt;tt&amp;gt;2&amp;lt;/tt&amp;gt;; the opposite occurs under traditional sorting. For case-insensitive natural sorting, use &amp;lt;tt&amp;gt;natcasesort( )&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
To sort the array in reverse order, use &amp;lt;tt&amp;gt;rsort( )&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;arsort( )&amp;lt;/tt&amp;gt;, which is like &amp;lt;tt&amp;gt;rsort( )&amp;lt;/tt&amp;gt; but also preserves keys. There is no &amp;lt;tt&amp;gt;natrsort( )&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;natcasersort( )&amp;lt;/tt&amp;gt;. You can also pass &amp;lt;tt&amp;gt;SORT_NUMERIC&amp;lt;/tt&amp;gt; into these functions.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Sorting an Array by a Computable Field|Recipe 4.18]] for sorting with a custom comparison function and [[PHP Cookbook/Arrays#Sorting Multiple Arrays|Recipe 4.19]] for sorting multiple arrays; documentation on &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/sort'', &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/asort'', &amp;lt;tt&amp;gt;natsort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/natsort'', &amp;lt;tt&amp;gt;natcasesort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/natcasesort'', &amp;lt;tt&amp;gt;rsort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/rsort'', and &amp;lt;tt&amp;gt;arsort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/arsort''.&lt;br /&gt;
&lt;br /&gt;
== Sorting an Array by a Computable Field ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to define your own sorting routine.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt; in combination with a custom comparison function:&lt;br /&gt;
&lt;br /&gt;
 // sort in reverse natural order&lt;br /&gt;
 function natrsort($a, $b) {&lt;br /&gt;
     return strnatcmp($b, $a);&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 $tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');&lt;br /&gt;
 usort($tests, 'natrsort');&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The comparison function must return a value greater that 0 if &amp;lt;tt&amp;gt;$a &amp;gt; $b&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; if &amp;lt;tt&amp;gt;$a == $b&amp;lt;/tt&amp;gt;, and a value less than 0 if &amp;lt;tt&amp;gt;$a &amp;lt; $b&amp;lt;/tt&amp;gt;. To sort in reverse, do the opposite. The function in the Solution, &amp;lt;tt&amp;gt;strnatcmp( )&amp;lt;/tt&amp;gt; , obeys those rules.&lt;br /&gt;
&lt;br /&gt;
To reverse the sort, instead of multiplying the return value of &amp;lt;tt&amp;gt;strnatcmp($a, $b)&amp;lt;/tt&amp;gt; by &amp;lt;tt&amp;gt;-1&amp;lt;/tt&amp;gt;, switch the order of the arguments to &amp;lt;tt&amp;gt;strnatcmp($b, $a)&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The sort function doesn't need to be a wrapper for an existing sort. For instance, the &amp;lt;tt&amp;gt;pc_date_sort( )&amp;lt;/tt&amp;gt; function, shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-2|Example 4-2]], shows how to sort dates.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-2&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-2. pc_date_sort( )'''&lt;br /&gt;
&lt;br /&gt;
 // expects dates in the form of &amp;quot;MM/DD/YYYY&amp;quot;&lt;br /&gt;
 function pc_date_sort($a, $b) {&lt;br /&gt;
     list($a_month, $a_day, $a_year) = explode('/', $a);&lt;br /&gt;
     list($b_month, $b_day, $b_year) = explode('/', $b);&lt;br /&gt;
 &lt;br /&gt;
     if ($a_year  &amp;gt; $b_year ) return  1;&lt;br /&gt;
     if ($a_year  &amp;lt; $b_year ) return -1;&lt;br /&gt;
 &lt;br /&gt;
     if ($a_month &amp;gt; $b_month) return  1;&lt;br /&gt;
     if ($a_month &amp;lt; $b_month) return -1;&lt;br /&gt;
 &lt;br /&gt;
     if ($a_day   &amp;gt; $b_day  ) return  1;&lt;br /&gt;
     if ($a_day   &amp;lt; $b_day  ) return -1;&lt;br /&gt;
 &lt;br /&gt;
     return 0;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 $dates = array('12/14/2000', '08/10/2001', '08/07/1999');&lt;br /&gt;
 usort($dates, 'pc_date_sort');&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While sorting, &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt; frequently recomputes the sort function's return values each time it's needed to compare two elements, which slows the sort. To avoid unnecessary work, you can cache the comparison values, as shown in &amp;lt;tt&amp;gt;pc_array_sort( )&amp;lt;/tt&amp;gt; in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-3|Example 4-3]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-3&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-3. pc_array_sort( )'''&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;function pc_array_sort($array, $map_func, $sort_func = '') {&lt;br /&gt;
    $mapped = array_map($map_func, $array);    // cache $map_func( ) values&lt;br /&gt;
&lt;br /&gt;
    if ('' == $sort_func) { &lt;br /&gt;
        asort($mapped);                        // asort( ) is faster then usort( )&lt;br /&gt;
    }  else { &lt;br /&gt;
        uasort($mapped, $sort_func);           // need to preserve keys&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    while (list($key) = each($mapped)) {&lt;br /&gt;
        $sorted[ ] = $array[$key];              // use sorted keys&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    return $sorted;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To avoid unnecessary work, &amp;lt;tt&amp;gt;pc_array_sort( )&amp;lt;/tt&amp;gt; uses a temporary array, &amp;lt;tt&amp;gt;$mapped&amp;lt;/tt&amp;gt;, to cache the return values. It then sorts &amp;lt;tt&amp;gt;$mapped&amp;lt;/tt&amp;gt;, using either the default sort order or a user-specified sorting routine. Importantly, it uses a sort that preserves the key/value relationship. By default, it uses &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; because &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; is faster than &amp;lt;tt&amp;gt;uasort( )&amp;lt;/tt&amp;gt;. (Slowness in &amp;lt;tt&amp;gt;uasort( )&amp;lt;/tt&amp;gt; is the whole reason for &amp;lt;tt&amp;gt;pc_array_sort( )&amp;lt;/tt&amp;gt; after all.) Finally, it creates a sorted array, &amp;lt;tt&amp;gt;$sorted&amp;lt;/tt&amp;gt;, using the sorted keys in &amp;lt;tt&amp;gt;$mapped&amp;lt;/tt&amp;gt; to index the values in the original array.&lt;br /&gt;
&lt;br /&gt;
For small arrays or simple sort functions, &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt; is faster, but as the number of computations grows, &amp;lt;tt&amp;gt;pc_array_sort( )&amp;lt;/tt&amp;gt; surpasses &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt;. The following example sorts elements by their string lengths — a relatively quick custom sort:&lt;br /&gt;
&lt;br /&gt;
 function pc_u_length($a, $b) {&lt;br /&gt;
     $a = strlen($a);&lt;br /&gt;
     $b = strlen($b);&lt;br /&gt;
 &lt;br /&gt;
     if ($a == $b) return  0;&lt;br /&gt;
     if ($a  &amp;gt; $b) return  1;&lt;br /&gt;
                   return -1;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 function pc_map_length($a) {&lt;br /&gt;
     return strlen($a);&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 $tests = array('one', 'two', 'three', 'four', 'five',&lt;br /&gt;
                'six', 'seven', 'eight', 'nine', 'ten');&lt;br /&gt;
 &lt;br /&gt;
 // faster for &amp;lt; 5 elements using pc_u_length()&lt;br /&gt;
 usort($tests, 'pc_u_length');&lt;br /&gt;
 &lt;br /&gt;
 // faster for &amp;gt;= 5 elements using pc_map_length()&lt;br /&gt;
 $tests = pc_array_sort($tests, 'pc_map_length');&lt;br /&gt;
&lt;br /&gt;
Here, &amp;lt;tt&amp;gt;pc_array_sort( )&amp;lt;/tt&amp;gt; is faster than &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt; once the array reaches five elements.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Sorting an Array|Recipe 4.17]] for basic sorting and [[PHP Cookbook/Arrays#Sorting Multiple Arrays|Recipe 4.19]] for sorting multiple arrays; documentation on &amp;lt;tt&amp;gt;usort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/usort'', &amp;lt;tt&amp;gt;asort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/asort'', and &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-map''.&lt;br /&gt;
&lt;br /&gt;
== Sorting Multiple Arrays ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to sort multiple arrays or an array with multiple dimensions.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use &amp;lt;tt&amp;gt;array_multisort( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
To sort multiple arrays simultaneously, pass multiple arrays to &amp;lt;tt&amp;gt;array_multisort( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $colors = array('Red', 'White', 'Blue');&lt;br /&gt;
 $cities = array('Boston', 'New York', 'Chicago');&lt;br /&gt;
 &lt;br /&gt;
 array_multisort($colors, $cities);&lt;br /&gt;
 print_r($colors);&lt;br /&gt;
 print_r($cities);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; Blue'''&lt;br /&gt;
                '''    [1] =&amp;gt; Red'''&lt;br /&gt;
                '''    [2] =&amp;gt; White'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
                '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [0] =&amp;gt; Chicago'''&lt;br /&gt;
                '''    [1] =&amp;gt; Boston'''&lt;br /&gt;
                '''    [2] =&amp;gt; New York'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
To sort multiple dimensions within a single array, pass the specific array elements:&lt;br /&gt;
&lt;br /&gt;
 $stuff = array('colors' =&amp;gt; array('Red', 'White', 'Blue'),&lt;br /&gt;
                'cities' =&amp;gt; array('Boston', 'New York', 'Chicago'));&lt;br /&gt;
 &lt;br /&gt;
 array_multisort($stuff['colors'], $stuff['cities']);&lt;br /&gt;
 print_r($stuff);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [colors] =&amp;gt; Array'''&lt;br /&gt;
                '''        ('''&lt;br /&gt;
                '''            [0] =&amp;gt; Blue'''&lt;br /&gt;
                '''            [1] =&amp;gt; Red'''&lt;br /&gt;
                '''            [2] =&amp;gt; White'''&lt;br /&gt;
                '''        )'''&lt;br /&gt;
 &lt;br /&gt;
                '''    [cities] =&amp;gt; Array'''&lt;br /&gt;
                '''        ('''&lt;br /&gt;
                '''            [0] =&amp;gt; Chicago'''&lt;br /&gt;
                '''            [1] =&amp;gt; Boston'''&lt;br /&gt;
                '''            [2] =&amp;gt; New York'''&lt;br /&gt;
                '''        )'''&lt;br /&gt;
 &lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
To modify the sort type, as in &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt;, pass in &amp;lt;tt&amp;gt;SORT_REGULAR&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;SORT_NUMERIC&amp;lt;/tt&amp;gt;, or &amp;lt;tt&amp;gt;SORT_STRING&amp;lt;/tt&amp;gt; after the array. To modify the sort order, unlike in &amp;lt;tt&amp;gt;sort( )&amp;lt;/tt&amp;gt;, pass in &amp;lt;tt&amp;gt;SORT_ASC&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;SORT_DESC&amp;lt;/tt&amp;gt; after the array. You can also pass in both a sort type and a sort order after the array.&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_multisort( )&amp;lt;/tt&amp;gt; function can sort several arrays at once or a multidimensional array by one or more dimensions. The arrays are treated as columns of a table to be sorted by rows. The first array is the main one to sort by; all the items in the other arrays are reordered based on the sorted order of the first array. If items in the first array compare as equal, the sort order is determined by the second array, and so on.&lt;br /&gt;
&lt;br /&gt;
The default sorting values are &amp;lt;tt&amp;gt;SORT_REGULAR&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;SORT_ASC&amp;lt;/tt&amp;gt;, and they're reset after each array, so there's no reason to pass either of these two values, except for clarity.&lt;br /&gt;
&lt;br /&gt;
 $numbers = array(0, 1, 2, 3);&lt;br /&gt;
 $letters = array('a', 'b', 'c', 'd');&lt;br /&gt;
 array_multisort($numbers, SORT_NUMERIC, SORT_DESC,&lt;br /&gt;
                 $letters, SORT_STRING , SORT_DESC);&lt;br /&gt;
&lt;br /&gt;
This example reverses the arrays.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Sorting an Array|Recipe 4.17]] for simple sorting and [[PHP Cookbook/Arrays#Sorting an Array by a Computable Field|Recipe 4.18]] for sorting with a custom function; documentation on &amp;lt;tt&amp;gt;array_multisort( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-multisort''.&lt;br /&gt;
&lt;br /&gt;
== Sorting an Array Using a Method Instead of a Function ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to define a custom sorting routine to order an array. However, instead of using a function, you want to use an object method.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Pass in an array holding a class name and method in place of the function name:&lt;br /&gt;
&lt;br /&gt;
 usort($access_times, array('dates', 'compare'));&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
As with a custom sort function, the object method needs to take two input arguments and return 1, 0, or -1, depending if the first parameter is larger than, equal to, or less than the second:&lt;br /&gt;
&lt;br /&gt;
 class pc_sort {&lt;br /&gt;
     // reverse-order string comparison&lt;br /&gt;
     function strrcmp($a, $b) {&lt;br /&gt;
         return strcmp($b, $a);&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 usort($words, array('pc_sort', 'strrcmp'));&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Classes and Objects|Chapter 7]] for more on classes and objects; [[PHP Cookbook/Arrays#Sorting an Array by a Computable Field|Recipe 4.18]] for more on custom sorting of arrays.&lt;br /&gt;
&lt;br /&gt;
== Randomizing an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to scramble the elements of an array in a random order.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If you're running PHP 4.3 or above, use &amp;lt;tt&amp;gt;shuffle( )&amp;lt;/tt&amp;gt; :&lt;br /&gt;
&lt;br /&gt;
 shuffle($array);&lt;br /&gt;
&lt;br /&gt;
If you're running an earlier version, use the &amp;lt;tt&amp;gt;pc_array_shuffle( )&amp;lt;/tt&amp;gt; function shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-4|Example 4-4]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-4&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-4. pc_array_shuffle( )'''&lt;br /&gt;
&lt;br /&gt;
 function pc_array_shuffle($array) {&lt;br /&gt;
     $i = count($array);&lt;br /&gt;
 &lt;br /&gt;
     while(--$i) {&lt;br /&gt;
         $j = mt_rand(0, $i);&lt;br /&gt;
 &lt;br /&gt;
         if ($i != $j) {&lt;br /&gt;
             // swap elements&lt;br /&gt;
             $tmp = $array[$j];&lt;br /&gt;
             $array[$j] = $array[$i];&lt;br /&gt;
             $array[$i] = $tmp;&lt;br /&gt;
         }&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     return $array;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's an example:&lt;br /&gt;
&lt;br /&gt;
 $cards = range(1,52); // deal out 52 &amp;quot;cards&amp;quot;&lt;br /&gt;
 $cards = pc_array_shuffle($cards);&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
There's already a &amp;lt;tt&amp;gt;shuffle( )&amp;lt;/tt&amp;gt; function in PHP to shuffle arrays, but as of PHP 4.2.2, it doesn't do its job correctly. The built-in shuffling algorithm tends to favor certain permutations more than others. Elements end up looking randomized, but since each element doesn't have the same chance of ending up in each position, it's not a true shuffle. This is fixed in PHP 4.3.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;tt&amp;gt;pc_array_shuffle( )&amp;lt;/tt&amp;gt; , known as the Fisher-Yates shuffle, equally distributes the elements throughout the array. Use it if you run a version of PHP earlier than 4.3. Unlike &amp;lt;tt&amp;gt;shuffle( )&amp;lt;/tt&amp;gt;, this function returns the scrambled array instead of modifying it in-place. It also requires a tightly packed array with integer keys.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Shuffling a Deck of Cards|Recipe 4.22]] for a function that simulates shuffling a deck of cards; documentation on &amp;lt;tt&amp;gt;shuffle( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/shuffle''.&lt;br /&gt;
&lt;br /&gt;
== Shuffling a Deck of Cards ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to shuffle a deck of cards and deal them out.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Create a array of 52 integers, shuffle them, and map them to cards:&lt;br /&gt;
&lt;br /&gt;
 $suits = array('Clubs', 'Diamonds', 'Hearts', 'Spades');&lt;br /&gt;
 $cards = array('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King');&lt;br /&gt;
 &lt;br /&gt;
 $deck = pc_array_shuffle(range(0, 51));&lt;br /&gt;
 &lt;br /&gt;
 while (($draw = array_pop($deck)) != NULL) {&lt;br /&gt;
     print  $cards[$draw / 4] . ' of ' . $suits[$draw % 4] . &amp;quot;\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
This code uses the &amp;lt;tt&amp;gt;pc_array_shuffle( )&amp;lt;/tt&amp;gt; function from [[PHP Cookbook/Arrays#Randomizing an Array|Recipe 4.21]].&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Here, a pair of arrays, &amp;lt;tt&amp;gt;$suits&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;$cards&amp;lt;/tt&amp;gt;, is created to hold the English representation of a card. The numbers &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; through &amp;lt;tt&amp;gt;51&amp;lt;/tt&amp;gt; are randomly arranged and assigned to &amp;lt;tt&amp;gt;$deck&amp;lt;/tt&amp;gt;. To deal a card, just pop them off the top of the array, treating the array like a literal deck of cards.&lt;br /&gt;
&lt;br /&gt;
It's necessary to add the check against &amp;lt;tt&amp;gt;NULL&amp;lt;/tt&amp;gt; inside the &amp;lt;tt&amp;gt;while&amp;lt;/tt&amp;gt;, otherwise the loop terminates when you draw the zeroth card. If you modify the deck to contain the numbers 1 through 52, the mathematics of deciding which number belongs to which card becomes more complex.&lt;br /&gt;
&lt;br /&gt;
To deal multiple cards at once, call &amp;lt;tt&amp;gt;array_slice( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 array_slice($deck, $cards * -1);&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Randomizing an Array|Recipe 4.21]] for a function that randomizes an array; documentation on &amp;lt;tt&amp;gt;array_slice( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-slice''.&lt;br /&gt;
&lt;br /&gt;
== Removing Duplicate Elements from an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to eliminate duplicates from an array.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If the array is already complete, use &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; , which returns a new array that contains no duplicate values:&lt;br /&gt;
&lt;br /&gt;
 $unique = array_unique($array);&lt;br /&gt;
&lt;br /&gt;
If you create the array while processing results, here is a technique for numerical arrays:&lt;br /&gt;
&lt;br /&gt;
 foreach ($_REQUEST['fruits'] as $fruit) {&lt;br /&gt;
     if (!in_array($array, $fruit)) { $array[ ] = $fruit; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here's one for associative arrays:&lt;br /&gt;
&lt;br /&gt;
 foreach ($_REQUEST['fruits'] as $fruit) {&lt;br /&gt;
     $array[$fruit] = $fruit;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Once processing is completed, &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; is the best way to eliminate duplicates. But, if you're inside a loop, you can eliminate the duplicate entries from appearing by checking if they're already in the array.&lt;br /&gt;
&lt;br /&gt;
An even faster method than using &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; is to create a hybrid array in which the key and the value for each element are the same. This eliminates the linear check of &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt; but still allows you to take advantage of the array family of functions that operate over the values of an array instead of the keys.&lt;br /&gt;
&lt;br /&gt;
In fact, it's faster to use the associative array method and then call &amp;lt;tt&amp;gt;array_values( )&amp;lt;/tt&amp;gt; on the result (or, for that matter, &amp;lt;tt&amp;gt;array_keys( )&amp;lt;/tt&amp;gt; , but &amp;lt;tt&amp;gt;array_values( )&amp;lt;/tt&amp;gt; is slightly faster) than to create a numeric array directly with the overhead of &amp;lt;tt&amp;gt;in_array( )&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-unique''.&lt;br /&gt;
&lt;br /&gt;
== Finding the Union, Intersection, or Difference of Two Arrays ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You have a pair of arrays, and you want to find their union (all the elements), intersection (elements in both, not just one), or difference (in one but not both).&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
To compute the union:&lt;br /&gt;
&lt;br /&gt;
 $union = array_unique(array_merge($a, $b));&lt;br /&gt;
&lt;br /&gt;
To compute the intersection:&lt;br /&gt;
&lt;br /&gt;
 $intersection = array_intersect($a, $b);&lt;br /&gt;
&lt;br /&gt;
To find the simple difference:&lt;br /&gt;
&lt;br /&gt;
 $difference = array_diff($a, $b);&lt;br /&gt;
&lt;br /&gt;
And for the symmetric difference:&lt;br /&gt;
&lt;br /&gt;
 $difference = array_merge(array_diff($a, $b), array_diff($b, $a));&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
Many necessary components for these calculations are built into PHP, it's just a matter of combining them in the proper sequence.&lt;br /&gt;
&lt;br /&gt;
To find the union, you merge the two arrays to create one giant array with all values. But, &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt; allows duplicate values when merging two numeric arrays, so you call &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; to filter them out. This can leave gaps between entries because &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; doesn't compact the array. It isn't a problem, however, as &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;each( )&amp;lt;/tt&amp;gt; handle sparsely filled arrays without a hitch.&lt;br /&gt;
&lt;br /&gt;
The function to calculate the intersection is simply named &amp;lt;tt&amp;gt;array_intersection( )&amp;lt;/tt&amp;gt; and requires no additional work on your part.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt; function returns an array containing all the unique elements in &amp;lt;tt&amp;gt;$old&amp;lt;/tt&amp;gt; that aren't in &amp;lt;tt&amp;gt;$new&amp;lt;/tt&amp;gt;. This is known as the ''simple difference'':&lt;br /&gt;
&lt;br /&gt;
 $old = array('To', 'be', 'or', 'not', 'to', 'be');&lt;br /&gt;
 $new = array('To', 'be', 'or', 'whatever');&lt;br /&gt;
 $difference = array_diff($old, $new);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [3] =&amp;gt; not'''&lt;br /&gt;
                '''    [4] =&amp;gt; to'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
The resulting array, &amp;lt;tt&amp;gt;$difference&amp;lt;/tt&amp;gt; contains &amp;lt;tt&amp;gt;'not'&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;'to'&amp;lt;/tt&amp;gt;, because &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt; is case-sensitive. It doesn't contain &amp;lt;tt&amp;gt;'whatever'&amp;lt;/tt&amp;gt; because it doesn't appear in &amp;lt;tt&amp;gt;$old&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
To get a reverse difference, or in other words, to find the unique elements in &amp;lt;tt&amp;gt;$new&amp;lt;/tt&amp;gt; that are lacking in &amp;lt;tt&amp;gt;$old&amp;lt;/tt&amp;gt;, flip the arguments:&lt;br /&gt;
&lt;br /&gt;
 $old = array('To', 'be', 'or', 'not', 'to', 'be');&lt;br /&gt;
 $new = array('To', 'be', 'or', 'whatever');&lt;br /&gt;
 $reverse_diff = array_diff($new, $old);&lt;br /&gt;
 '''Array'''&lt;br /&gt;
                '''('''&lt;br /&gt;
                '''    [3] =&amp;gt; whatever'''&lt;br /&gt;
                ''')'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;$reverse_diff&amp;lt;/tt&amp;gt; array contains only &amp;lt;tt&amp;gt;'whatever'&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you want to apply a function or other filter to &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt;, roll your own diffing algorithm:&lt;br /&gt;
&lt;br /&gt;
 // implement case-insensitive diffing; diff -i&lt;br /&gt;
 &lt;br /&gt;
 $seen = array( );&lt;br /&gt;
 foreach ($new as $n) {&lt;br /&gt;
     $seen[strtolower($n)]++;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 foreach ($old as $o) {&lt;br /&gt;
     $o = strtolower($o);&lt;br /&gt;
     if (!$seen[$o]) { $diff[$o] = $o; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The first &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; builds an associative array lookup table. You then loop through &amp;lt;tt&amp;gt;$old&amp;lt;/tt&amp;gt; and, if you can't find an entry in our lookup, add the element to &amp;lt;tt&amp;gt;$diff&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It can be a little faster to combine &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt; with &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $diff = array_diff(array_map('strtolower', $old), array_map('strtolower', $new));&lt;br /&gt;
&lt;br /&gt;
The symmetric difference is what's in &amp;lt;tt&amp;gt;$a&amp;lt;/tt&amp;gt;, but not &amp;lt;tt&amp;gt;$b&amp;lt;/tt&amp;gt;, and what's in &amp;lt;tt&amp;gt;$b&amp;lt;/tt&amp;gt;, but not &amp;lt;tt&amp;gt;$a&amp;lt;/tt&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 $difference = array_merge(array_diff($a, $b), array_diff($b, $a));&lt;br /&gt;
&lt;br /&gt;
Once stated, the algorithm is straightforward. You call &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt; twice and find the two differences. Then you merge them together into one array. There's no need to call &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt;, since you've intentionally constructed these arrays to have nothing in common.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
Documentation on &amp;lt;tt&amp;gt;array_unique( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-unique'', &amp;lt;tt&amp;gt;array_intersect( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-intersect'', &amp;lt;tt&amp;gt;array_diff( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-diff'', &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-merge'', and &amp;lt;tt&amp;gt;array_map( )&amp;lt;/tt&amp;gt; at ''http://www.php.net/array-map''.&lt;br /&gt;
&lt;br /&gt;
== Finding All Element Combinations of an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You want to find all combinations of sets containing some or all of the elements in an array, also called the ''power set'' .&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use the &amp;lt;tt&amp;gt;pc_array_power_set( )&amp;lt;/tt&amp;gt; function shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-5|Example 4-5]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-5&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-5. pc_array_power_set( )'''&lt;br /&gt;
&lt;br /&gt;
 function pc_array_power_set($array) {&lt;br /&gt;
     // initialize by adding the empty set&lt;br /&gt;
     $results = array(array( ));&lt;br /&gt;
 &lt;br /&gt;
     foreach ($array as $element)&lt;br /&gt;
         foreach ($results as $combination)&lt;br /&gt;
             array_push($results, array_merge(array($element), $combination));&lt;br /&gt;
 &lt;br /&gt;
     return $results;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This returns an array of arrays holding every combination of elements, including the empty set. For example:&lt;br /&gt;
&lt;br /&gt;
 $set = array('A', 'B', 'C');&lt;br /&gt;
 $power_set = pc_array_power_set($set);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;tt&amp;gt;$power_set&amp;lt;/tt&amp;gt; contains eight arrays:&lt;br /&gt;
&lt;br /&gt;
 array( );&lt;br /&gt;
 array('A');&lt;br /&gt;
 array('B');&lt;br /&gt;
 array('C');&lt;br /&gt;
 array('A', 'B');&lt;br /&gt;
 array('A', 'C');&lt;br /&gt;
 array('B', 'C');&lt;br /&gt;
 array('A', 'B', 'C');&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
First, you include the empty set, &amp;lt;tt&amp;gt;{}&amp;lt;/tt&amp;gt; , in the results. After all, one potential combination of a set is to take no elements from it.&lt;br /&gt;
&lt;br /&gt;
The rest of this function relies on the nature of combinations and PHP's implementation of &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;. Each new element added to the array increases the number of combinations. The new combinations are all the old combinations alongside the new element; a two-element array containing &amp;lt;tt&amp;gt;A&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;B&amp;lt;/tt&amp;gt; generates four possible combinations: &amp;lt;tt&amp;gt;{}&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;{A}&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;{B}&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;{A,&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;B}&amp;lt;/tt&amp;gt;. Adding &amp;lt;tt&amp;gt;C&amp;lt;/tt&amp;gt; to this set keeps the four previous combinations but also adds four new combinations: &amp;lt;tt&amp;gt;{C}&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;{A,&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;C}&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;{B,&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;C}&amp;lt;/tt&amp;gt;, and &amp;lt;tt&amp;gt;{A,&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;B,&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;C}&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Therefore, the outer &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loop moves through every element of the list; the inner &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loops through every previous combination created by earlier elements. This is the tricky bit; you need to know exactly how PHP behaves during a &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;array_merge( )&amp;lt;/tt&amp;gt; function combines the element with the earlier combinations. Note, however, the &amp;lt;tt&amp;gt;$results&amp;lt;/tt&amp;gt; array added to the new array with &amp;lt;tt&amp;gt;array_push()&amp;lt;/tt&amp;gt; is the one that's cycled through in the &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt;. Normally, adding entries to &amp;lt;tt&amp;gt;$results&amp;lt;/tt&amp;gt; causes an infinite loop, but not in PHP, because PHP operates over a copy of the original list. But, when you pop back up a level to the outer loop, and reexecute the &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; with the next &amp;lt;tt&amp;gt;$element&amp;lt;/tt&amp;gt;, it's reset. So, you can operate directly on &amp;lt;tt&amp;gt;$results&amp;lt;/tt&amp;gt; in place and use it as a stack to hold your combinations. By keeping everything as arrays, you're given far more flexibility when it comes to printing out or further subdividing the combinations at a later time.&lt;br /&gt;
&lt;br /&gt;
To remove the empty set, replace the opening line of:&lt;br /&gt;
&lt;br /&gt;
 // initialize by adding the empty set&lt;br /&gt;
 $results = array(array( ));&lt;br /&gt;
&lt;br /&gt;
with:&lt;br /&gt;
&lt;br /&gt;
 // initialize by adding the first element&lt;br /&gt;
 $results = array(array(array_pop($array)));&lt;br /&gt;
&lt;br /&gt;
Since a one-element array has only one combination — itself — popping off an element is identical to making the first pass through the loop. The double &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; statements don't know they're really starting their processing with the second element in the array.&lt;br /&gt;
&lt;br /&gt;
To print the results with tabs between elements inside the combination and returns between each combination, use the following:&lt;br /&gt;
&lt;br /&gt;
 $array = array('Adam', 'Bret', 'Ceff', 'Dave');&lt;br /&gt;
 &lt;br /&gt;
 foreach (pc_array_power_set($array) as $combination) {&lt;br /&gt;
     print join(&amp;quot;\t&amp;quot;, $combination) . &amp;quot;\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here's how to print only three-element sized combinations:&lt;br /&gt;
&lt;br /&gt;
 foreach (pc_array_power_set($set) as $combination) {&lt;br /&gt;
     if (3 == count($combination)) {&lt;br /&gt;
         print join(&amp;quot;\t&amp;quot;, $combination) . &amp;quot;\n&amp;quot;;&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Iterating over a large set of elements takes a long time. A set of &amp;lt;tt&amp;gt;n&amp;lt;/tt&amp;gt; elements generates 2&amp;lt;sup&amp;gt;n+1&amp;lt;/sup&amp;gt; sets. In other words, as &amp;lt;tt&amp;gt;n&amp;lt;/tt&amp;gt; grows by 1, the number of elements doubles.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Finding All Permutations of an Array|Recipe 4.26]] for a function that finds all permutation of an array.&lt;br /&gt;
&lt;br /&gt;
== Finding All Permutations of an Array ==&lt;br /&gt;
&lt;br /&gt;
=== Problem ===&lt;br /&gt;
&lt;br /&gt;
You have an array of elements and want to compute all the different ways they can be ordered.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
Use one of the two permutation algorithms discussed next.&lt;br /&gt;
&lt;br /&gt;
=== Discussion ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;pc_permute()&amp;lt;/tt&amp;gt; function shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-6|Example 4-6]] is a PHP modification of a basic recursive function.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-6&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-6. pc_permute( )'''&lt;br /&gt;
&lt;br /&gt;
 function pc_permute($items, $perms = array( )) {&lt;br /&gt;
     if (empty($items)) { &lt;br /&gt;
         print join(' ', $perms) . &amp;quot;\n&amp;quot;;&lt;br /&gt;
     }  else {&lt;br /&gt;
         for ($i = count($items) - 1; $i &amp;gt;= 0; --$i) {&lt;br /&gt;
              $newitems = $items;&lt;br /&gt;
              $newperms = $perms;&lt;br /&gt;
              list($foo) = array_splice($newitems, $i, 1);&lt;br /&gt;
              array_unshift($newperms, $foo);&lt;br /&gt;
              pc_permute($newitems, $newperms);&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
 pc_permute(split(' ', 'she sells seashells'));&lt;br /&gt;
 '''she sells seashells'''&lt;br /&gt;
                '''she seashells sells'''&lt;br /&gt;
                '''sells she seashells'''&lt;br /&gt;
                '''sells seashells she'''&lt;br /&gt;
                '''seashells she sells'''&lt;br /&gt;
                '''seashells sells she'''&lt;br /&gt;
             &lt;br /&gt;
&lt;br /&gt;
However, while this recursion is elegant, it's inefficient, because it's making copies all over the place. Also, it's not easy to modify the function to return the values instead of printing them out without resorting to a global variable.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;pc_next_permutation( )&amp;lt;/tt&amp;gt; function shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-7|Example 4-7]], however, is a little slicker. It combines an idea of Mark-Jason Dominus from ''Perl Cookbook'' by Tom Christianson and Nathan Torkington (O'Reilly) with an algorithm from Edsger Dijkstra's classic text ''A Discipline of Programming'' (Prentice-Hall).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-7&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-7. pc_next_permutation( )'''&lt;br /&gt;
&lt;br /&gt;
 function pc_next_permutation($p, $size) {&lt;br /&gt;
     // slide down the array looking for where we're smaller than the next guy&lt;br /&gt;
     for ($i = $size - 1; $p[$i] &amp;gt;= $p[$i+1]; --$i) { }&lt;br /&gt;
 &lt;br /&gt;
     // if this doesn't occur, we've finished our permutations&lt;br /&gt;
     // the array is reversed: (1, 2, 3, 4) =&amp;gt; (4, 3, 2, 1)&lt;br /&gt;
     if ($i == -1) { return false; }&lt;br /&gt;
 &lt;br /&gt;
     // slide down the array looking for a bigger number than what we found before&lt;br /&gt;
     for ($j = $size; $p[$j] &amp;lt;= $p[$i]; --$j) { }&lt;br /&gt;
 &lt;br /&gt;
     // swap them&lt;br /&gt;
     $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;&lt;br /&gt;
 &lt;br /&gt;
     // now reverse the elements in between by swapping the ends&lt;br /&gt;
     for (++$i, $j = $size; $i &amp;lt; $j; ++$i, --$j) {&lt;br /&gt;
          $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     return $p;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 $set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells')&lt;br /&gt;
 $size = count($set) - 1;&lt;br /&gt;
 $perm = range(0, $size);&lt;br /&gt;
 $j = 0;&lt;br /&gt;
 &lt;br /&gt;
 do { &lt;br /&gt;
      foreach ($perm as $i) { $perms[$j][] = $set[$i]; }&lt;br /&gt;
 } while ($perm = pc_next_permutation($perm, $size) and ++$j);&lt;br /&gt;
 &lt;br /&gt;
 foreach ($perms as $p) {&lt;br /&gt;
     print join(' ', $p) . &amp;quot;\n&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Dominus's idea is that instead of manipulating the array itself, you can create permutations of integers. You then map the repositioned integers back onto the elements of the array to calculate the true permutation — a nifty idea.&lt;br /&gt;
&lt;br /&gt;
However, this technique still has some shortcomings. Most importantly, to us as PHP programmers, it frequently pops, pushes, and splices arrays, something that's very Perl-centric. Next, when calculating the permutation of integers, it goes through a series of steps to come up with each permutation; because it doesn't remember previous permutations, it therefore begins each time from the original permutation. Why redo work if you can help it?&lt;br /&gt;
&lt;br /&gt;
Dijkstra's algorithm solves this by taking a permutation of a series of integers and returning the next largest permutation. The code is optimized based upon that assumption. By starting with the smallest pattern (which is just the integers in ascending order) and working your way upwards, you can scroll through all permutations one at a time, by plugging the previous permutation back into the function to get the next one. There are hardly any swaps, even in the final swap loop in which you flip the tail.&lt;br /&gt;
&lt;br /&gt;
There's a side benefit. Dominus's recipe needs the total number of permutations for a given pattern. Since this is the factorial of the number of elements in the set, that's a potentially expensive calculation, even with memoization. Instead of computing that number, it's faster to return &amp;lt;tt&amp;gt;false&amp;lt;/tt&amp;gt; from &amp;lt;tt&amp;gt;pc_next_permutation( )&amp;lt;/tt&amp;gt; when you notice that &amp;lt;tt&amp;gt;$i&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;==&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;-1&amp;lt;/tt&amp;gt;. When that occurs, you're forced outside the array, and you've exhausted the permutations for the phrase.&lt;br /&gt;
&lt;br /&gt;
Two final notes of implementation. Since the size of the set is invariant, you capture it once using &amp;lt;tt&amp;gt;count( )&amp;lt;/tt&amp;gt; and pass it into &amp;lt;tt&amp;gt;pc_next_permutation( )&amp;lt;/tt&amp;gt;; this is faster than repeatedly calling &amp;lt;tt&amp;gt;count( )&amp;lt;/tt&amp;gt; inside the function. Also, since the set is guaranteed by its construction to have unique elements, i.e., there is one and only one instance of each integer, we don't need to need to check for equality inside the first two &amp;lt;tt&amp;gt;for&amp;lt;/tt&amp;gt; loops. However, you should include them in case you want to use this recipe on other numeric sets, in which duplicates might occur.&lt;br /&gt;
&lt;br /&gt;
=== See Also ===&lt;br /&gt;
&lt;br /&gt;
[[PHP Cookbook/Arrays#Finding All Element Combinations of an Array|Recipe 4.25]] for a function that finds the power set of an array; Recipe 4.19 in the ''Perl Cookbook'' (O'Reilly); [[PHP Cookbook/Dates and Times|Chapter 3]], ''A Discipline of Programming'' (Prentice-Hall).&lt;br /&gt;
&lt;br /&gt;
== Program: Printing an Array in a Horizontally Columned HTML Table ==&lt;br /&gt;
&lt;br /&gt;
Converting an array into a horizontally columned table places a fixed number of elements in a row. The first set goes in the opening table row, the second set goes in the next row, and so forth. Finally, you reach the final row, where you might need to optionally pad the row with empty table data cells.&lt;br /&gt;
&lt;br /&gt;
The function &amp;lt;tt&amp;gt;pc_grid_horizontal( )&amp;lt;/tt&amp;gt; , shown in [[PHP Cookbook/Arrays#phpckbk-CHP-4-EX-8|Example 4-8]], lets you specify an array and number of columns. It assumes your table width is 100%, but you can alter the &amp;lt;tt&amp;gt;$table_width&amp;lt;/tt&amp;gt; variable to change this.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-EX-8&amp;quot;&amp;gt;&lt;br /&gt;
'''Example 4-8. pc_grid_horizontal( )'''&lt;br /&gt;
&lt;br /&gt;
 function pc_grid_horizontal($array, $size) {&lt;br /&gt;
 &lt;br /&gt;
     // compute &amp;amp;lt;td&amp;gt; width %ages&lt;br /&gt;
     $table_width = 100;&lt;br /&gt;
     $width = intval($table_width / $size);&lt;br /&gt;
 &lt;br /&gt;
     // define how our &amp;amp;lt;tr&amp;gt; and &amp;amp;lt;td&amp;gt; tags appear&lt;br /&gt;
     // sprintf() requires us to use %% to get literal %&lt;br /&gt;
     $tr = '&amp;amp;lt;tr align=&amp;quot;center&amp;quot;&amp;gt;';&lt;br /&gt;
     $td = &amp;quot;&amp;amp;lt;td width=\&amp;quot;$width%%\&amp;quot;&amp;gt;%s&amp;amp;lt;/td&amp;gt;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
     // open table&lt;br /&gt;
     $grid = &amp;quot;&amp;amp;lt;table width=\&amp;quot;$table_width%\&amp;quot;&amp;gt;$tr&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
     // loop through entries and display in rows of size $sized&lt;br /&gt;
     // $i keeps track of when we need a new table tow&lt;br /&gt;
     $i = 0;&lt;br /&gt;
     foreach ($array as $e) {&lt;br /&gt;
         $grid .= sprintf($td, $e);&lt;br /&gt;
         $i++;&lt;br /&gt;
 &lt;br /&gt;
         // end of a row&lt;br /&gt;
         // close it up and open a new one&lt;br /&gt;
         if (!($i % $size)) {&lt;br /&gt;
             $grid .= &amp;quot;&amp;amp;lt;/tr&amp;gt;$tr&amp;quot;;&lt;br /&gt;
         }&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     // pad out remaining cells with blanks&lt;br /&gt;
     while ($i % $size) {&lt;br /&gt;
         $grid .= sprintf($td, '&amp;amp;amp;nbsp;');&lt;br /&gt;
         $i++;&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     // add &amp;amp;lt;/tr&amp;gt;, if necessary&lt;br /&gt;
     $end_tr_len = strlen($tr) * -1;&lt;br /&gt;
     if (substr($grid, $end_tr_len) != $tr) {&lt;br /&gt;
         $grid .= '&amp;amp;lt;/tr&amp;gt;';&lt;br /&gt;
     } else {&lt;br /&gt;
         $grid = substr($grid, 0, $end_tr_len);&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     // close table&lt;br /&gt;
     $grid .= '&amp;amp;lt;/table&amp;gt;';&lt;br /&gt;
 &lt;br /&gt;
     return $grid;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The function begins by calculating the width of each &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; as a percentage of the total table size. Depending on the number of columns and the overall size, the sum of the &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; widths might not equal the &amp;lt;tt&amp;gt;&amp;amp;lt;table&amp;gt;&amp;lt;/tt&amp;gt; width, but this shouldn't effect the displayed HTML in a noticeable fashion. Next, define the &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;&amp;amp;lt;tr&amp;gt;&amp;lt;/tt&amp;gt; tags, using &amp;lt;tt&amp;gt;printf&amp;lt;/tt&amp;gt;-style formatting notation. To get the literal &amp;lt;tt&amp;gt;%&amp;lt;/tt&amp;gt; needed for the &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; width percentage, use a double &amp;lt;tt&amp;gt;%%&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The meat of the function is the &amp;lt;tt&amp;gt;foreach&amp;lt;/tt&amp;gt; loop through the array in which we append each &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; to the &amp;lt;tt&amp;gt;$grid&amp;lt;/tt&amp;gt;. If you reach the end of a row, which happens when the total number of elements processed is a multiple of number of elements in a row, you close and then reopen the &amp;lt;tt&amp;gt;&amp;amp;lt;tr&amp;gt;&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you finish adding all the elements, you need to pad the final row with blank or empty &amp;lt;tt&amp;gt;&amp;amp;lt;td&amp;gt;&amp;lt;/tt&amp;gt; elements. Put a nonbreaking space inside the data cell instead of leaving it empty to make the table renders properly in the browser. Now, make sure there isn't an extra &amp;lt;tt&amp;gt;&amp;amp;lt;tr&amp;gt;&amp;lt;/tt&amp;gt; at the end of grid, which occurs when the number of elements is an exact multiple of the width (in other words, if you didn't need to add padding cells). Finally, you can close the table.&lt;br /&gt;
&lt;br /&gt;
For example, let's print the names of the 50 U.S. states in a six-column table:&lt;br /&gt;
&lt;br /&gt;
 // establish connection to database&lt;br /&gt;
 $dsn = 'mysql://user:password@localhost/table';&lt;br /&gt;
 $dbh = DB::connect($dsn);&lt;br /&gt;
 if (DB::isError($dbh)) { die ($dbh-&amp;gt;getMessage( )); }&lt;br /&gt;
 &lt;br /&gt;
 // query the database for the 50 states&lt;br /&gt;
 $sql = &amp;quot;SELECT state FROM states&amp;quot;;&lt;br /&gt;
 $sth = $dbh-&amp;gt;query($sql);&lt;br /&gt;
 &lt;br /&gt;
 // load data into array from database&lt;br /&gt;
 while ($row = $sth-&amp;gt;fetchRow(DB_FETCHMODE_ASSOC)) {&lt;br /&gt;
   $states[ ] = $row['state'];&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 // generate the HTML table&lt;br /&gt;
 $grid = pc_grid_horizontal($states, 6);&lt;br /&gt;
 &lt;br /&gt;
 // and print it out&lt;br /&gt;
 print $grid;&lt;br /&gt;
&lt;br /&gt;
When rendered in a browser, it looks like [[PHP Cookbook/Arrays#phpckbk-CHP-4-FIG-1|Figure 4-1]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;phpckbk-CHP-4-FIG-1&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 4-1. The United States of America'''&lt;br /&gt;
&lt;br /&gt;
[[Image:PHP Cookbook_I_4_tt286.png|The United States of America]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because 50 doesn't divide evenly by six, there are four extra padding cells in the last row.&lt;br /&gt;
== Notes ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Docbook2Wiki</name></author>	</entry>

	</feed>