This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Explore sorting multidimensional arrays using a particular inner key element. Dive deeper into sorting and using both array keys and their values to produce the desired results.
TAKE NOTE
When creating an array to use for sorting another array, there are a few things to keep in mind.
- Array keys MUST be unique.
- You can sort by either key or value
- Not all sort functions maintain key association
Loop Options
In PHP, a foreach loop is almost always the fastest, however, you should avoid creating unused variables which not only take up room on a computer, but also in a developers head.
foreach($arr as $key => $notUsed)
is about 50% to 60% faster than using
foreach(array_keys($arr) as $key)
The array_keys function may make it easier to understand what we are actually using from the array.
As another option, if you have additional conditions (such as only needing a certain number) that may keep you from looping through the entire array, it could be useful to use a while loop with the list and each functions to grab your results.
$newArray=array();
while (count($newArray) < 3 && list($key) = each($list)) {
$newArray[]=$key;
...
It's really up to you, your situation and your team, which option is best. PHP also includes many other array function that may be useful to your situation, such as array_multisort. We'll be learning more about functions, in the PHP Functions Course, but feel free to have some fun exploring array function , adding features and trying multiple ways to accomplish the same task.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up