Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP: Sort array by value, keep keys

Posted on 2011-09-20
2
Medium Priority
?
471 Views
Last Modified: 2012-05-12
How can I sort my array by values, while maintaining keys?

My code below sorts by the keys, not the values:
<pre><?php

$zzz=array();

$zzz['b']='Banana';
$zzz['z']='Cherry';
$zzz['m']='Apple';
$zzz['a']='Durian';

asort($zzz);

$zzz = array_merge(array('a'=>'Apple'),$zzz);

print_r($zzz);

?>
</pre>

Open in new window


I want this:

Array
(
    [m] => Apple
    [b] => Banana
    [z] => Cherry
    [a] => Durian
 )

Open in new window

0
Comment
Question by:hankknight
  • 2
2 Comments
 
LVL 4

Accepted Solution

by:
MattJellings earned 2000 total points
ID: 36569473
Hi hankknight,

I've had a quick look and from what I can see the asort() function is the correct one to use, but I belive the array_merge line you are using afterwards is affecting the order of your array.

For example, try performing another asort() after the array_merge() as follows:

$zzz=array(); 
 
$zzz['b']='Banana'; 
$zzz['z']='Cherry'; 
$zzz['m']='Apple'; 
$zzz['a']='Durian'; 
 
asort($zzz); 
 
$zzz = array_merge(array('a'=>'Apple'),$zzz); 
 
echo '<pre>'; print_r($zzz); echo '</pre>'; 

asort($zzz);

echo '<pre>'; print_r($zzz); echo '</pre>';

Open in new window


This gives the following (note the second print_r statement outputs the array in your desired order.

Array
(
    [a] => Durian
    [m] => Apple
    [b] => Banana
    [z] => Cherry
)
Array
(
    [m] => Apple
    [b] => Banana
    [z] => Cherry
    [a] => Durian
)

Open in new window


If this is in fact the case then I would suggest performing a single asort() after your have finished running any required array_merge() functions.

I hope this helps with your problem.

Cheers

Matt
0
 
LVL 4

Expert Comment

by:MattJellings
ID: 36569516
Just to provide a bit more information for you, the PHP manual page for array_merge() states the following:

"Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one."

"If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."

This would explain the problem.

What I believe is happening is you are first creating the array $zzz and then you are appending this array onto your array('a'=>'Apple') created on line 10.

This is first creating a new array, with a single element who's key is 'a' and value is 'Apple'.  The array_merge() is then appending the existing $zzz array onto the end.   Leaving 'a'=>'Apple' as the first element in the array.  Subsequently, as the documentation states, because your $zzz array has an existing key 'a' who's value is 'Durian' this is overwriting 'a'.

My apologies, I'm struggling to explain it however hopefully it makes some sense to you.

Cheers

Matt
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question