Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Writing PHP

By Neil Williams
2007-11-11


Building, sorting, reversing and flipping arrays

Array functions

Create and return an array of values:
quicker than using $myarray[0] = "value1" etc.

$array1 = array("value1",4,"value3");
$array2 = array("value1",3,"string value");
$array3 = array("value3","any value");

To create an associative array, use => to link the key to the corresponding value:

$names_array = array("Bob" => "Jones","Fred" => "Bloggs",
"June" => "Smith")

To help find the differences between two or more arrays, array_diff() returns an array containing only the values from $array1 that do NOT occur in any of the other arrays.

$diff_array = array_diff($array1, $array2, $array3);

$diff_array contains only one value, 4 in $diff_array[1] indicating that the first value $array1[0] = value1 was matched, the second value $array1[1] = 4 was different and the third value $array1[2] = value3 was matched.

An array containing names from an address book could contain firstnames as keys and family names as values - the $names_array above. Sorting the array using asort(), sorts on the values - the family name. To sort the array on firstnames, use ksort().

asort($names_array);

sorts the array by the value - familyname. $names_array now contains:

Fred Bloggs
Bob Jones
June Smith

ksort() sorts the array by the key - firstname. $names_array now contains:

Bob Jones
Fred Bloggs
June Smith

To reverse the order, use rsort() for simple arrays and arsort() for associative arrays. To reverse the order of a ksort() requires two operations - use ksort() as normal and then use array_reverse() to reverse the ksort. To convert keys into values and the values into keys, use array_flip().

arsort($names_array);
June Smith
Bob Jones
Fred Bloggs

ksort($names_array);
$names_array = array_reverse($names_array);
June Smith
Fred Bloggs
Bob Jones

$names_array = array_flip($names_array);
Smith June
Bloggs Fred
Jones Bob


Tutorial Pages:
» What can PHP do?
» PHP output
» PHP and HTTP: headers and variables
» No need for CGI access
» Preventing and solving bugs in PHP
» Checking user input for dubious or erroneous values
» Read remote files, read and write local files on the server
» Common PHP functions
» Building, sorting, reversing and flipping arrays
» Current time, date calculations, timestamp formats
» PHP string functions


Copyright © Neil Williams


 | Bookmark
Related Tutorials:
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1
» Desktop Application Development with PHP-GTK

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources