Arrays in PHP are unlike those of any other common programming language
Best described as a melding of the arrays of C/Java with the hashes of Perl
The ultimate in flexible built-in data structures!!
Like a Perl hash, arrays in PHP have two parts:
a key and a value
$list[0] =17; $list[2]="This is a nice day"; $list[]=33; #this element key will be 3
$list2 = array(12, 34, 45, 56); /* traditional array with 4 elements with the keys 0, 1, 2, 3 */ $list3 = array( 1 => 12, 3 => 34, 4 => 45, 7 => 56); /* an array with four elements with the keys 1, 3, 4, 7 */ $list4 = array(); # an empty array $list5 = array("Tom" => 13, "Dick" => 18, "Jerry" => 24); /* an array with three elements with the keys "Tom", "Dick", "Jerry" */ $list6 = array( "make" => "volvo", "model" => "245", "year" => 1974, 3 => "Sold" ); /* PHP arrays can be mixtures of tarditional arrays and hashes */
$val = $list3[3]; # $val has a value of 34 $val = $list5['Tom']; # $val is 13 $val = $list6[3]; # $val is "Sold"
$keys6 = array_keys($list6); /* $keys6 holds the keys of $list6 */ $valu6 = array_values($list6); /* $valu6 holds the values of $list6 */
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN" "http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd"> <!-- sorting.php An example to illustrate sorting functions --> <html> <head> <title> Sorting Functions </title> </head> <body> <?php $original = array("Fred"=> 31, "Al" => 27, "Gandalf" => "wizzard", "Betty" => 42, "Frodo" => "hobbit" ); ?> <h4>Original Array</h4> <?php foreach ($original as $key => $value ) print("[$key] => $value <br />"); $new = $original; sort($new); ?> <h4>Array Sorted by <tt>sort</tt></h4> <?php foreach ($new as $key => $value ) print("[$key] => $value <br />"); $new = $original; sort($new, SORT_NUMERIC); ?> <h4>Array Sorted by <tt>sort, SORT_NUMERIC</tt></h4> <?php foreach ($new as $key => $value ) print("[$key] => $value <br />"); $new = $original; rsort($new); ?> <h4>Array Sorted by <tt>rsort</tt></h4> <?php foreach ($new as $key => $value ) print("[$key] => $value <br />"); $new = $original; asort($new); ?> <h4>Array Sorted by <tt>asort</tt></h4> <?php foreach ($new as $key => $value ) print("[$key] => $value <br />"); $new = $original; arsort($new); ?> <h4>Array Sorted by <tt>arsort</tt></h4> <?php foreach ($new as $key => $value ) print("[$key] => $value <br />"); ?> </body> </html>
An example to illustrate sorting fucntions
| Origins and Uses of PHP |
| Overview of PHP |
| General Syntactic Characteristics |
| Primitives, Operations, and Expressions |
| Output |
| Control Statements |
| Arrays |
| Functions |
| Pattern Matching |
| Form Handling |
| Files |
| Cookies |
| Session Tracking |