Solved

PHP: Sort array by value, keep keys

Posted on 2011-09-20
2
415 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 500 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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Encode a password 2 39
Re-imbursement Claim System 3 25
windows 10 bash shell 4 37
confirm popup before record delete takes place 87 25
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now