|
Helping ordinary people create extraordinary websites! |
Writing PHPBy Neil Williams2007-11-11
Building, sorting, reversing and flipping arrays Array functionsCreate and return an array of values: $array1 = array("value1",4,"value3");
To create an associative array, use => to link the key to the corresponding value: $names_array = array("Bob" => "Jones","Fred" => "Bloggs",
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 ksort() sorts the array by the key - firstname. $names_array now contains: Bob Jones 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); 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 |
|