(click anywhere to close)
OPEN MENU

[PHP] Arrays II

category: Website | course: PHP | difficulty:

Last chapter discussed the most important functions and operators you can use with arrays, but they still can’t do everything. Just as I did with strings, I want to use this chapter to outline other extremely useful functions to use with arrays – such as cutting a subarray, searching for specific keys or values, and sorting the array.

Subarrays

We’ve already seen how we can select a single element of the array, but what if we want to select multiple elements? Well, then your selection is a list, which means it is a subarray! (Just as with substrings.)

To get part of an array, use

array_slice($array, offset [, length, preserve_keys]);

The slice starts at index offset, and takes length amount of elements. If it’s not set, it will end the slice at the end of the array. Note that this does not alter the original array; it simply returns the slice so you can use it.

If you’re working with indexed arrays, PHP will automatically reorder the keys of the slice so that they start at index 0. Set preserve_keys to true if you want to prevent this.

//Oh no, somehow, some wrong information entered the array
$tweet_information = ["just setting up my twttr", "21 March 2006", "Jack", "250 retweets", "PANDAS ARE COOL", "CRISPS ARE DELICIOUS"];

//Luckily, we can slice out the right information
$tweet_information = array_slice($tweet_information, 0, 4);

//The result is ["just setting up my twttr", "22 January 2016", "Jack", "250 retweets"];

Alternatively, you can use the following syntax to remove a portion of the array and perhaps replace it:

array_splice($array, offset [, length, $replacement_array]);

The elements from the $replacement_array are inserted at the offset index. Note that it only replaces the elements it removes – so, if you remove say five elements, and the replacement array contains ten, it will only insert the first five.

The function itself returns the elements that have been removed, but it also alters the original array (unlike the array_slice() function).

$user = ["downvotes received" => 24, "upvotes received" => 7, "comments" => 5, "forum posts" => 15];

//If we only care about his/her votes, we could remove the other two elements
array_splice($user, 2);

//Or we can replace them with other information regarding votes
array_splice($user, 2, 2, ["downvotes given" => 3, "upvotes given" => 8]);

//Or we can do something with the elements we've removed
$comments_and_posts = array_splice($user, 2);

Searching

To check if a value exists in an array, use

in_array($needle, $haystack [, $strict]);

This searches for the value $needle in the array $haystack. If you set the third parameter to true, it also requires that the data type is the same. The functions returns true if it finds the value, and false otherwise.

$grocery_list = ["Butter", "Pizza", "Chocolate", "Milk"];

//If there's milk on our grocery list...
if(in_array("Milk", $grocery_list)) {
	//...notify the milk man!
}

Sometimes, though, you want to get the key that belongs to a certain value. For that, use

array_search($needle, $haystack [, $strict]);

If it can’t find the value, and therefore can’t find the key, it returns false.

$grocery_list = ["Butter", "Pizza", "Chocolate", "Milk"];

var_dump( array_search("Milk", $grocery_list) ); //Prints int(3)
var_dump( array_search("Pancakes", $grocery_list) ); //Prints bool(false). Aww, no pancakes today.

Lastly, to check if a certain key is within an array, use

array_key_exists($needle, $haystack);
$comment = ["message" => "Hey Juan, nice holiday photos! Really dig your beard.", 
			"timestamp" => "May 30 2016, 2PM",
			"from" => "Ginty",
			"reply" => true];

if(array_key_exists("reply", $comment)){
	//notify Juan that he has a reply to his fabulous holiday photographs.
}

Compare & Replace

The following functions can be used for performing certain operations between multiple arrays:

Function

Description

array_diff($arr1, $arr2)

Returns the values from $arr1 that are not present in $arr2

array_intersect($arr1, $arr2)

Returns the values from $arr1 that are also present in $arr2

array_combine($keys, $values)

Returns an array with the elements from $keys as keys, and elements from $values as values.

array_merge($arr1, $arr2)

Appends the elements from $arr2 to the end of $arr1. Duplicate keys will be set to the value from $arr2.

array_replace($arr1, $arr2)

Replaces values from $arr1 with values from $arr2, if they have the same key.

//Say we're writing a system for Santa Claus to manage his presents
$wishlist_papa = ["Beer", "Television", "Cat"];
$wishlist_mama = ["Lipstick", "Mirror", "Cat"];

//Result: [Beer, Television, Lipstick, Mirror]
array_diff($wishlist_papa, $wishlist_mama); 

//Result: [Cat]
array_intersect($wishlist_papa, $wishlist_mama); 

//Result: [Beer => Lipstick, Television => Mirror, Cat => Cat]
array_combine($wishlist_papa, $wishlist_mama); 

//Result: [Beer, Television, Lipstick, Mirror, Cat]
array_merge($wishlist_papa, $wishlist_mama); 

//Result: [Lipstick, Mirror, Cat]
array_replace($wishlist_papa, $wishlist_mama); 

//Obviously, Santa Claus is going to use the intersection to minimize his costs

All methods, except for combine, can actually accept as many arrays as you want, as long as you provide at least two.

Sorting

Up until now, the order of an array is simply the order in which you put in the values, and it hasn’t really mattered much. There are many cases imaginable, however, where sorting an array is a crucial action. Obvious cases are when you want to display lists in alphabetical order, but you also need it to display blog posts from newest to oldest or display comments ordered on how many upvotes they have.

To do so, PHP has these functions available to us:

Function

Description

sort($arr)

Sort an array in ascending order

rsort($arr)

Sort an array in descending order

asort($arr)

Sort an associative array in ascending order, according to value

ksort($arr)

Sort an associative array in ascending order, according to key

arsort($arr)

Sort an associative array in descending order, according to value

krsort($arr)

Sort an associative array in descending order, according to key

shuffle($arr)

Randomly orders the elements of an array.

How does PHP sort values? First it sorts alphabetically (strings), then numerically (integers, floats, Booleans). For sorting alphabetically, it uses lexicographical ordering, which simply means that it uses the same ordering as dictionaries – first check the first character, then the next one, then the next one, and so on. For sorting numerically, the order is the same as the one you’re used to – 0, 1, 2, and so on.

$users = ["Ginty", "Juan", "Mark", "Avocado", "BATMAN"];

sort($users);  //Results in ["Avocado", "BATMAN", "Ginty", "Juan", "Mark"];
rsort($users); //Results in ["Mark", "Juan", "Ginty", "BATMAN", "Avocado"];

Only lowercase characters are supported for string ordering.

Lastly, PHP also has an easy function to reverse the current order of an array:

array_reverse($arr [, $preserve_keys]);

The $preserve_keys parameter, if set to true, will preserve numeric indexes. String keys are always preserved.

$users = ["Ginty", "Juan", "Mark", "Avocado", "BATMAN"];

array_reverse($users); 
//Results in ["BATMAN", "Avocado", "Mark", "Juan", "Ginty"];

array_reverse($users, true); 
/* Results in 
   Array (
	  ["4"] => "BATMAN", 
	  ["3"] => "Avocado", 
	  ["2"] => "Mark", 
	  ["1"] => "Juan", 
	  ["0"] => "Ginty", 
  )
*/
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)