Writing PHP - 9: PHP Array functions

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().


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().

June Smith
Bob Jones
Fred Bloggs

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

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

This is part of www.codehelp.co.uk Copyright © 1998-2004 Neil Williams
See the file about.html for copying conditions.