PHP Functions - Changing, Spliting, Slicing, and Sorting Arrays - Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Chapter 4. PHP Functions - Changing, Spliting, Slicing, and Sorting Arrays

After completing this chapter, the student will be able to…

Create a simple PHP program which changes the contents of an existing array

Create a simple PHP program which splits an array based on a value or comparison

Create a simple PHP program which slices an array based on a value or comparison

Create a simple PHP program which sorts an array based on a value, comparison, or key

In this chapter we will take a brief look at the PHP functions that are available to change, split, slice, and sort arrays. Many of these functions work with multiple array types (single, multi-dimensional, and/or associative).

All descriptions of the following functions are provided by the on-line PHP manual available at www.php.net. Brief examples using each function and a description of the results of these examples are provided. These examples are only ment to get your feet wet. For a more detailed description of the functions shown, and for more examples, visit the on-line PHP manual.

Changing Array Contents

array_change_key_case – changes the key to uppercase or lowercase

“Returns an array with its keys lower or uppercased, orFALSEifarray is not an array.”

Syntax:

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example:

$test_array = array(‘firstname’ => ‘Jeff’,

‘lastname’ => ‘Smith’);

print_r(array_change_key_case($test_array, CASE_UPPER)));

Output:

Array

(

[FIRSTNAME] => Jeff

[LASTNAME] => Smith

)

In this example, the keys (FIRSTNAME, LASTNAME) are uppercased.

array_fill — fill an array with values

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Syntax:

array array_fill ( int $start_index , int $num , mixed $value )

First parameter is the starting index. Second parameter is the ending index.

Example:

$default_array = array_fill(1, 8, 'default');

print_r($default_array);

Output:

Array (

[1] => default

[2] => default

[3] => default

[4] => default

[5] => default

[6] => default

[7] => default

[8] => default

)

In this example, 1 and 8 are passed, providing the starting and ending keys. Default is also passed providing the value used to fill the array.

array_fill_keys — fills an array with values, specifying keys

“Fills an array with the value of the value parameter, using the values of the keys array as keys.”

Syntax:

array array_fill_keys ( array $keys , mixed $value )

Example:

$keys = array('first_name', 'last_name', 'address', 'city', 'state', 'zip');

$default_array = array_fill_keys($keys, 'default');

print_r($default_array);

Output:

Array (

[first_name] => default

[last_name] => default

[address] => default

[city] => default

[state] => default

[zip] => default

)

In this example, the $keys array is used to supply the key. The word ‘default’ is used to fill each position.

array_filter — filters elements of an array using a callback function

“Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.”

This function can be used in several ways to filter out content you don’t want in your array.

You can create a function to filter out unwanted data types that exist in the array or use existing PHP functions.

Syntax:

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip' => 30001);

function filter_array($unfiltered_value)

{

if(is_string($unfiltered_value))

{

return $unfiltered_value;

}

}

print_r(array_filter($first_array, "filter_array"));

Output:

Array (

[first_name] => Pete

[last_name] => Smith

[address] => 123 Main Street

[city] => Atlanta

[state] => GA

)

This example would filter out anything that is not a string.

Without a function, it will filter out empty strings, NULL, or FALSE.

Example:

$first_array = array('first_name' => '' , 'last_name' => NULL , 'address' => FALSE , 'city' => 'Atlanta', 'state' => 'GA', 'zip' => 30001);

print_r(array_filter($first_array));

Output:

Array (

[city] => Atlanta

[state] => GA

[zip] => 30001

)

A PHP compare function can be used instead of a user defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

array_flip — exchanges all keys with their associated values in an array

“array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.”

Syntax:

array array_flip ( array $array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

$result = array_flip($first_array);

print_r($result);

Output:

Array (

[Pete] => first_name

[Smith] => last_name

[123 Main Street] => address

[Atlanta] => city

[GA] => state

[30001] => zip_code

)

In this example, the keys and values in array $first_array are reversed.

array_pad — pads an array to the specified length with a value

“array_pad() returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left.”

Syntax:

array array_pad ( array $array , int $size , mixed $value )

Example:

$first_array = array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', '30001');

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' ,'GA' , '30001');

$first_array = array_pad($first_array, 8, "No Value");

$second_array = array_pad($second_array, -8, "No Value");

print_r($first_array);

print_r($second_array);

Output:

Array (

[0] => Pete

[1] => Smith

[2] => 123 Main Street

[3] => Atlanta

[4] => GA

[5] => 30001

[6] => No Value

[7] => No Value

)

Array (

[0] => No Value

[1] => No Value

[2] => Sally

[3] => Parisi

[4] => 101 South Street

[5] => Atlanta

[6] => GA

[7] => 30001

)

first_array now has two additional elements at the end of the array. The length of the original array was 6. The padding size entered was 8. Thus, two extra positions are created.

Second_array now has two additional elements at the front of the array. The padding size entered was -8.

array_pop — pops the element off the end of array

“array_pop() pops and returns the last value of the array, shortening the array by one element.”

Syntax:

mixed array_pop ( array &$array )

Example:

$first_array = array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', '30001');

print array_pop($first_array);

print_r($first_array);

Output:

30001

Array (

[0] => Pete

[1] => Smith

[2] => 123 Main Street

[3] => Atlanta

[4] => GA

)

The last element of $first_array is pulled from the array and displayed via the print statement. The array size is now one less than originally.

array_push — pushes one or more elements onto the end of array

“array_push() treats an array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.”

Syntax:

int array_push ( array &$array , mixed $value1 [, mixed $... ] )

Example:

$customer_record = array (

array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', 30001),

array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001)

);

$customer_info = array('Be' , 'Happy' , '111 North Street' , 'Atlanta' , 'GA' , 30001);

array_push($customer_record, $customer_info);

print_r($customer_record);

Output:

Array (

[0] =>

Array (

[0] => Pete [1] => Smith [2] => 123 Main Street

[3] => Atlanta [4] => GA [5] => 30001

)

[1] =>

Array (

[0] => Sally [1] => Parisi [2] => 101 South Street

[3] => Atlanta [4] => GA [5] => 30001

)

[2] =>

Array (

[0] => Be [1] => Happy [2] => 111 North Street

[3] => Atlanta [4] => GA [5] => 30001

)

)

array_push adds the Be Happy array to the end of the existing array.

array_shift — shifts an element off the beginning of an array

“array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.”

Syntax:

mixed array_shift ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001);

array_shift($first_array);

array_shift($second_array);

print_r($first_array);

print_r($second_array);

Output:

Array (

[last_name] => Smith

[address] => 123 Main Street

[city] => Atlanta [state] => GA

[zip_code] => 30001

)

Array (

[0] => Parisi

[1] => 101 South Street

[2] => Atlanta

[3] => GA

[4] => 30001

)

In $first_array, first_name has been removed from the front of the array. In $second_array, Sally has been removed and the indexes have been renumbered beginning at 0.

array_unshift — prepends one or more elements to the beginning of an array

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. “

Syntax:

int array_unshift ( array &$array , mixed $value1 [, mixed $... ] )

Example:

$first_array = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta', 'CA', 30001);

print(array_unshift($first_array, "770-777-7777", "adm@no.co"));

print_r($first_array);

Output:

8

Array (

[0] => 770-777-7777

[1] => adm@no.co

[2] => Pete

[3] => Smith

[4] => 123 Main Street

[5] => Atlanta

[6] => CA

[7] => 30001

)

array_unshift will append items to the end of the array. The function will return the new size of the array. In this example, two items are added to the end of $first_array.

compact — creates an array containing variables and their values

“For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().

Any strings that are not set will simply be skipped.”

Syntax:

array compact ( mixed $varname1 [, mixed $... ] )

Example:

$first_name = "Pete";

$last_name = "Smith";

$address = "123 Main Street";

$city = "Atlanta";

$state = "GA";

$zip_code = 30001;

$keys = array("first_name", "last_name", "address", "city", "state", "zip_code");

$first_array = compact($keys);

print_r($first_array);

Output:

Array (

[first_name] => Pete

[last_name] => Smith

[address] => 123 Main Street

[city] => Atlanta

[state] => GA

[zip_code] => 30001

)

compact will build a array from existing variable names that are passed. It will use the variable names for the keys creating an associative array. In this example an array of the variable names is passed in which pulls the values in the variables and creates the array shown. If the variable does not exist, it will ignore it.

range — creates an array containing a range of elements

Syntax:

array range ( mixed $start , mixed $end [, number $step = 1 ] )

Example:

print_r(range(1,10));

Output:

Array (

[0] => 1

[1] => 2

[2] => 3

[3] => 4

[4] => 5

[5] => 6

[6] => 7

[7] => 8

[8] => 9

[9] => 10

)

range provides a quick way to generate sequential values for an array.

Example:

print_r(range('A','F'));

Output:

Array (

[0] => A

[1] => B

[2] => C

[3] => D

[4] => E

[5] => F

)

You are not limited to just numerical values.

Example:

print_r(range('F','A'));

Output:

Array (

[0] => F

[1] => E

[2] => D

[3] => C

[4] => B

[5] => A

)

You are also not limited to ascending order.

Spliting and Slicing Arrays

array_chunk — splits an array into chunks

“Chunks an array into arrays withsizeelements. The last chunk may contain less thansize elements.”

Syntax:

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example:

$test_array = array(‘Jeff’, ‘Smith’, ‘123 Main Street’, ‘Atlanta’, ‘GA’, ‘30001’);

print_r(array_chunk($test_array, 2));

Output:

Array

(

[0] => Array

(

[0] => Jeff

[1] => Smith

)

[1] => Array

(

[0] => 123 Main Street

[1] => GA

)

[2] => Array

(

[0] => 30001

)

)

Passing 2 into the function splits the original array into a two-dimensional array with 3 elements.

Example:

$test_array = array(‘Jeff’, ‘Smith’, ‘123 Main Street’, ‘Atlanta’, ‘GA’, ‘30001’);

print_r(array_chunck($test_array, 2));

Output:

Array

(

[0] => Array

(

[0] => Jeff

[1] => Smith

)

[1] => Array

(

[2] => 123 Main Street

[3] => GA

)

[2] => Array

(

[4] => 30001

)

)

In this example, the original keys (subscripts) are retained within the new two-dimensional array.

array_slice — extracts a slice of the array

“array_slice() returns the sequence of elements from the array as specified by the offset and length parameters.”

Syntax:

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

Example:

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001);

print_r(array_slice($second_array, 2));

print_r(array_slice($second_array, -2, 1));

print_r(array_slice($second_array, 0, 2));

print_r(array_slice($second_array, 2, -1));

print_r(array_slice($second_array, 2, -1, true));

Output:

Array (

[0] => 101 South Street

[1] => Atlanta

[2] => GA

[3] => 30001

)

Array (

[0] => GA

)

Array (

[0] => Sally

[1] => Parisi

)

Array (

[0] => 101 South Street

[1] => Atlanta

[2] => GA

)

Array (

[2] => 101 South Street

[3] => Atlanta

[4] => GA

)

Passing just a 2, will return all values starting at position 2 (101 South Street, Atlanta, 30001).

Passing a -2 and 1, will slice from the right instead of left, starting at the second to last right position and return one value (GA).

Passing a 0 and 2, will start at position 0 and return two values (Sally, Parisi).

Passing a 2, and -1, will start at position 2 and return all items up to the second to last right most item (101 South Street, Atlanta).

Passing 2, -1, and TRUE will return the same as the previous example, except the original indexes are retained.

array_splice — removes a portion of the array and replace it with something else

“Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.”

Syntax:

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement = array() ]] )

Example:

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001);

print_r(array_splice($second_array, 2));

print_r(array_splice($second_array, 0, 1));

Output:

Array (

[0] => 101 South Street

[1] => Atlanta

[2] => GA

[3] => 30001

)

Array (

[0] => Sally

)

In the first example, 2 is passed which requests that the contents of the array $second_array is retained starting at index 2 (the address).

In the second example, 0 and 1 are passed indicating that starting at position 0, 1 item should be retained (the first name).

Sorting Arrays

array_multisort — sorts multiple or multi-dimensional arrays

“array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

Sorting type flags:

◦ SORT_REGULAR - compare items normally (don't change types)

◦ SORT_NUMERIC - compare items numerically

◦ SORT_STRING - compare items as strings

◦ SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()

◦ SORT_NATURAL - compare items as strings using "natural ordering" like natsort()

◦ SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively”

Syntax:

bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )

Example:

$first_array = array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', ‘30001’);

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' ,'GA' , ‘3000’1);

array_multisort($first_array, SORT_ASC,

$second_array, SORT_DESC );

print_r($first_array);

print_r($second_array);

Output:

Array (

[0] => 123 Main Street

[1] => 30001

[2] => Atlanta

[3] => GA

[4] => Pete

[5] => Smith

)

Array (

[0] => 101 South Street

[1] => 30001

[2] => Atlanta

[3] => GA

[4] => Sally

[5] => Parisi

)

In this example,

$first_array values are sorted as strings in ascending order. String numbers (123, 30001) are first in sorting order followed by ‘A’, ‘G’, ‘P’, and ‘S’.

$second_array values are sorted as strings in descending order. String numbers (123, 30001) are first in sorting order followed by ‘A’, ‘G’, ‘S’, and ‘P’.

array_reverse — returns an array with elements in reverse order

“Takes an input array and returns a new array with the order of the elements reversed.”

Syntax:

array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example:

first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

$second_array = array('Sally' , 'Parisi' , '101 South Street' , 'Atlanta' , 'GA' , 30001);

print_r(array_reverse($first_array));

print_r(array_reverse($second_array));

print_r(array_reverse($second_array, TRUE));

Output:

Array (

[zip_code] => 30001

[state] => GA

[city] => Atlanta

[address] => 123 Main Street

[last_name] => Smith

[first_name] => Pete

)

Array (

[0] => 30001

[1] => GA

[2] => Atlanta

[3] => 101 South Street

[4] => Parisi

[5] => Sally

)

Array (

[5] => 30001

[4] => GA

[3] => Atlanta

[2] => 101 South Street

[1] => Parisi

[0] => Sally

)

In this example the elements in $first_array are returned in reverse order. $second_array is also returned in reverse order. When passing TRUE in the second parameter, the original numerical indexes are retain.

arsort — sorts an array in reverse order and maintain index association

“This function sorts an array such that array indices maintain their correlation with the array elements they are associated with.

This is used mainly when sorting associative arrays where the actual element order is significant.”

Syntax:

bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

arsort($first_array);

print_r($first_array);

Output:

Array (

[zip_code] => 30001

[last_name] => Smith

[first_name] => Pete

[state] => CA

[city] => Atlanta

[address] => 123 Main Street

)

arsort is used with associative arrays to sort values. It sorts values in reverse alphabetical order. In this example the zip code is listed first because it is numeric. The remaining values are in reverse order. The keys (subscripts) are maintained.

asort — sorts an array and maintain index association

“This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.”

Syntax:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

asort($first_array);

print_r($first_array);

Output:

Array (

[address] => 123 Main Street

[city] => Atlanta

[state] => CA

[first_name] => Pete

[last_name] => Smith

[zip_code] => 30001

)

The function asort is used with associative arrays to sort values. It sorts values in alphabetic order. In this example zip code is listed last because it is numeric. The remaining values are in alphabetic order. The keys (subscripts) are maintained.

krsort — sorts an array by key in reverse order

“Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.”

Syntax:

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

krsort($first_array);

print_r($first_array);

Output:

Array (

[zip_code] => 30001

[state] => CA

[last_name] => Smith

[first_name] => Pete

[city] => Atlanta

[address] => 123 Main Street

)

krsort sorts keys in reverse alphabetic order. In this example, zip_code is now first in the array, and address is last.

ksort — sorts an array by key

“Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.”

Syntax:

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

ksort($first_array);

print_r($first_array);

Output:

Array (

[address] => 123 Main Street

[city] => Atlanta

[first_name] => Pete

[last_name] => Smith

[state] => CA

[zip_code] => 30001

)

ksort sorts array kesy in alphabetic order. In this example, address is now first in the array, and zip_code is last.

natcasesort — sorts an array using a case insensitive "natural order" algorithm

“This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".”

Syntax:

bool natcasesort ( array &$array )

Example:

$name_array = array("Pete", "peter", "jones", "Jones");

natcasesort($name_array);

print_r($name_array);

Output:

Array (

[3] => Jones

[2] => jones

[0] => Pete

[1] => peter

)

natcasesort arranges items in a way that is more natural to humans. In this example all the Jones values appear before any of the Peter values. It ignores case.

natsort — sorts an array using a "natural order" algorithm

“This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".”

Syntax:

bool natsort ( array &$array )

Example:

$name_array = array("Pete", "peter", "jones", "Jones");

natsort($name_array);

print_r($name_array);

Output:

Array (

[3] => Jones

[0] => Pete

[2] => jones

[1] => peter

)

natsort sorts in a human natural way. However, it does not ignore case. In the example above all uppercase words occur before lowercase. However, notice that the keys (subscripts) are retained, unlike sort.

rsort — sorts an array in reverse order

“This function sorts an array in reverse order (highest to lowest).”

Syntax:

bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

rsort($first_array);

print_r($first_array);

Output:

Array (

[0] => 30001

[1] => Smith

[2] => Pete

[3] => CA

[4] => Atlanta

[5] => 123 Main Street

)

rsort sorts the values in an array in reverse alphabetic order. It does not maintain the keys (subscripts) from the original array. As seen from the example, numerical values would exist first in the sorted array.

shuffle — shuffles an array

“This function shuffles (randomizes the order of the elements in) an array.”

Syntax:

bool shuffle ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

shuffle($first_array);

print_r($first_array);

Output:

Array (

[0] => CA

[1] => Pete

[2] => 123 Main Street

[3] => 30001

[4] => Smith

[5] => Atlanta

)

shuffle randomly sorts the order of the values in an array. It does not maintain the keys (subscripts).

sort — sorts an array

“This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.”

Syntax:

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

sort($first_array);

print_r($first_array);

Output:

Array (

[0] => 123 Main Street

[1] => Atlanta

[2] => CA

[3] => Pete

[4] => Smith

[5] => 30001

)

sort shuffles the array into alphabetic order, it does not maintain the keys (subscripts). String values naturally occur first in the sort order before numerical values as shown in the example.

uasort — sorts an array with a user-defined comparison function and maintain index association

“This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.”

Syntax:

bool uasort ( array &$array , callable $value_compare_func )

Example:

function value_compare($first_value, $second_value)

{

if ($first_value == $second_value)

return 0;

else if ($first_value > $second_value)

return 1;

else

return -1;

}

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

uasort($first_array, 'value_compare');

print_r($first_array);

Output:

Array (

[address] => 123 Main Street

[city] => Atlanta

[state] => CA

[first_name] => Pete

[last_name] => Smith

[zip_code] => 30001

)

uasort sorts the array in ascending order of the values in each element as determined by a user supplied function which evaluates what is equal, greater than, or less than. The keys (subscripts) are maintained from the original array.

The user can modify the comparison shown (such as using === instead of ==) to determine what is ‘equal’. The user supplied function must return a value < 0, 0, and > 0, as shown in the example function.

uasort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

uksort — sorts an array by keys using a user-defined comparison function

“uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.”

Syntax:

bool uksort ( array &$array , callable $key_compare_func )

Example:

function key_compare($first_key, $second_key)

{

if ($first_key == $second_key)

return 0;

else if ($first_key > $second_key)

return 1;

else

return -1;

}

uksort($first_array, "key_compare");

print_r($first_array);

Output:

Array (

[address] => 123 Main Street

[city] => Atlanta

[first_name] => Pete

[last_name] => Smith

[state] => CA

[zip_code] => 30001

)

uksort sorts an array in ascending order by keys (subscripts) based on the comparison provided by a user supplied function. The function must determine what is equal, what is greater than, and what is less than. The keys (subscripts) from the original array are maintained.

The user can modify the comparison shown (such as using === instead of ==) to determine what is ‘equal’. The user supplied function must return a value < 0, 0, and > 0, as shown in the example function.

uksort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

usort — sorts an array by values using a user-defined comparison function

“This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.”

Syntax:

bool usort ( array &$array , callable $value_compare_func )

Example:

function value_compare($first_value, $second_value)

{

if ($first_value == $second_value)

return 0;

else if ($first_value > $second_value)

return 1;

else

return -1;

}

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

usort($first_array, 'value_compare');

print_r($first_array);

Output:

Array (

[0] => 123 Main Street

[1] => Atlanta

[2] => CA

[3] => Pete

[4] => Smith

[5] => 30001

)

usort sorts the array in ascending order of the values in each element as determined by a user supplied function which evaluates what is equal, greater than, or less than. The keys (subscripts) are not maintained from the original array.

The user can modify the comparison shown (such as using === instead of ==) to determine what is ‘equal’. The user supplied function must return a value < 0, 0, and > 0, as shown in the example function.

usort($first_array, "strcmp”);

print_r($first_array);

A PHP compare function can be used instead of a user defined function. These could include strcmp, strcasecmp, strncasecmp, substrcomp, or other PHP comparison functions that return < 0, 0, or > 0 as a result.

Exercises

1. Create a PHP program containing an array of all the first and last names of the students in your class. Sort the array by last name in alphabetic order. Also sort the array in reverse order.

2. Split the array from #1 into two arrays; one containing first names, the other containing last names.