PHP provides some built-in functions to make array operations easy for programmers such as sorting, searching, or other array operations.
Array Sorting Functions In PHP
Function | What It Does |
array_multisort() | Sorts multiple or multidimensional arrays |
arsort() | Reverse sorts associative arrays alphabetically by value. The index association remains intact. |
asort() | Sorts associative arrays alphabetically by value. The index association remains intact. |
krsort() | Reverse sorts associative arrays alphabetically by key. The index association remains intact. |
ksort() | Sorts associative arrays alphabetically by key. The index association remains intact. |
natcasesort() | Sorts an array using a case–‐insensitive “natural order” algorithm |
natsort() | Sorts an array using a “natural order” algorithm |
rsort() | Sorts an array in reverse order |
shuffle() | Shuffles an array |
sort() | Sorts an array |
uasort() | Sorts an array with a user–‐defined comparison function and maintains index association |
uksort() | Sorts an array by keys using a user–‐defined comparison function |
usort() | Sorts an array by values using a user–‐defined comparison function |
Example 1: Sorting an array in ascending order
<?php
$list=array(34,54,65,76,87,56,45,34,23,54,67);
sort($list);
for ($i=0; $i <count($list) ; $i++) {
echo $list[$i]." ";
}
?>
Output:
23 34 34 45 54 54 56 65 67 76 87
Array Sort Flags in PHP
Flag | What It Does |
SORT_LOCALE_STRING | Compares items as strings, based on the current locale |
SORT_NUMERIC | Compares items numerically |
SORT_REGULAR | Compares items normally (does not change types) |
SORT_STRING | Compares items as strings |
Array Manipulation Functions
Function | Explanation |
array_count_values() | Returns an array consisting of the values of an array and the number of times each value occurs in an array $hash_count = array_count_values( array(“a”,”b”, “a”,”a”)); // Creates an associative array with “a” and “b” as the two keys and the number of times each occurs in the array (the associated value) |
array_fill(5, 6,“php”) | Starting from 5 index, fill 6 values, all values “php” |
array_key_exists() | Checks to see if a specified key exists in an array. |
array_keys() | Returns all the keys of an associative array as an array. $array_of_keys = array_keys(“apples”, “pears”, “peaches”, “plums”); //Returns0,1,2,3 $array_of_keys = array_keys(“Title”=>”King”, “Name”=>”Barbar”); //Returns “Title”, “Name” |
array_pad() | Pads an array to the specified length with a value |
array_reverse() | Returns an array with the elements in reverse order. |
array_values() | returns an array with all the values of the original array $animals=array(“tiger”, “lion”, “camel”,”elephant”); $array_of_values=array_values($animals); //Returns:”tiger”,”lion”,”camel”,”elephant” |
array_walk() | Applies a user function to every element of an array. |
count() | Returns the number of elements in an array. |
each() | returns the current key–value pair in an array, and moves to the next element, making that the current element. The returned value is an array of two alternating values to represent each key and its corresponding value. To access the array elements, you can use either 0 and 1 to represent each key and value, or the keywords key and value to do the same thing. Used with a looping construct, each element of the array can be accessed until the array has reached its end. The reset() function sets the internal array pointer back to the beginning of the array if you want to access the array elements again. $colors=array(‘red’,’green’, ‘blue’,’yellow’); while($array = each($colors)) { // echo $array[0].” => ” . $array[1]. “<br />”; echo $array[‘key’].” => ” . $array[‘value’]. “<br />”; } |
explode() | Splits up a string by a specified delimiter and creates an array of strings $fruit = explode(” “, “apples pears peaches plums”); $fruit = explode(“|”, “apples|pears|peaches|plums”,3);//creates a 3 element array |
implode() | Creates a string by gluing together array elements by a specific separator $stats_array = array(‘name’, ‘ssn’, ‘phone’); $stats_string = implode(“,”, $stats_array); |
in_array() | Checks if a value exists in an array |
is_array() | Takes one parameter and returns true or false depending on whether the parameter passed is an array. |
join() | Alias for implode() |
range(start,end,step) | range(1, 5) // returns 1, 2, 3, 4, 5 range(1, 10, 2) //returns 1, 3, 5, 7, 9 range(15, 0, -5) //15, 10, 5, 0 range(-2, -8) //-2, -3, -4, -5, -6, -7, -8 range(‘a’,’c’) //a, b, c |
rsort() | Reverse sorts an array alphabetically. Elements will be assigned to new index numbers. |
shuffle() | Randomly sorts the array. For the order to be sorted differently each time, the random number generator needs to be seeded with rsand(). $numbers = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); shuffle($numbers); |
sizeof() | Returns the size of the array, same as count() |
sort() | Sorts an array alphabetically. Elements will be assigned to new index numbers. |
split() | Splits up a string into an array by a regular expression |
list() | extracts elements from a numeric array (with index starting at 0) and assigns them to individual variables. Its arguments are a comma-separated list of variable names $swatch = array(‘blue’, ‘#33A1C9’, ‘peacock’); list($color, $code, $name) = $swatch; // Create variables from array list($color, $code) = $swatch; // Ignore ‘peacock’ list($color, , $name)=$swatch; // Skip ‘#33A1C9’ |
extract() | creates variables from any associative array. The variables are named after the keys, and the values assigned to them are the same as the correspnding values in the associative array. $television = array(“model”=>”Pan PX-44BBCCSTV”,”type”=>”plasma”, “color”=>”charcoal bezel”, “size”=>”42 in. widescreen”); extract($television);// Create variables from keys print ” Model number after <em>extract(): $model</em><p>”; print “Values of variables created by <em>extract():<br />”; print “$model, $type, $color, $size</em><br />”; |
array_rand() | The array_rand() function lets you select one or more random entries from an array. It takes an array as its argument and by default returns one random key or index value. If a second optional numeric argument is given, you can specify how many random keys to pick from the array, and an array of that number of random keys will be returned $colors=array(“red”,”green”,”blue”,”yellow”); $random= array_rand($colors); // Returns a random color $random= array_rand($colors, 2); // Returns two random colors print $colors[$random[0]]; print $colors[$random[1]]; |
Example 2: Using explode function in PHP
<?php
$list="A brown quick, fox jumps, over the lazy dog";
$newlist=explode(' ', $list);
for ($i=0; $i <count($newlist) ; $i++) {
echo $newlist[$i]. "<br>";
}
?>
Output:
A
brown
quick,
fox
jumps,
over
the
lazy
dog
Removing an Array and its Elements in PHP
Function | What It Does |
array_pop() | Removes and returns the last element of an array |
array_shift() | Removes and returns the first element of an array |
array_splice() | Removes and/or replaces elements in an array |
array_unique() | Removes duplicates from an array |
unset() | Removes an entire array |
Adding Elements to an Array in PHP
Function | What It Does |
array_push() | Pushes a new element(s) onto the end of the array |
array_splice() | Removes or adds elements |
array_unshift() | Adds a new element(s) to the beginning of the array |
Combining and Merging Arrays in PHP
Function | What It Does |
array_combine() | returns an array made up of keys and values. The keys of the new array are made up of the values from the first array and the values associated with the new keys are made up of the values from the second array (PHP 5). The function returns FALSE if there are an unequal number of values in either of the arrays used as arguments. |
array_merge() | joins two or more arrays together to return a single array. The values of one array are appended to the end of the previous array. |
Array Operators in PHP
Operator | Function | Meaning |
$a + $b | Union | Union Of $a And $b |
$a == $b | Equality | TRUE If $a And $b Have the same key–value pairs |
$a === $b | Identity | TRUE If $a And $b Have the same key–value pairs in the same order and of the same types |
$a != $b | Inequality | TRUE If $a Is not equal to $b |
$a <> $b | Inequality | TRUE If $a Is not equal to $b |
$a !== $b | Nonidentity | TRUE if $a is not identical to $b |
Support us by sharing this post