1

In PHP you can do this to order an array of strings by their size:

usort($parts, function($a, $b) {
    return strlen($b) - strlen($a);
});

How do I order an array of strings by size but if two strings are the same size, order them by their index in the original array.

eg:

I a o delicious cake

becomes:

delicious cake I a o

At the moment with my current code it becomes:

delicious cake o a i

1
  • check my answer below. I hope it is what you exactly want @BarneyChambers Commented Aug 9, 2017 at 8:49

3 Answers 3

3

Please use this method for sort array.

<?php
$parts = "I a o delicious cake";
$parts = explode(" ",$parts);
array_multisort(array_map('strlen', $parts),SORT_DESC, $parts); // this is for DESC order
//array_multisort(array_map('strlen', $parts),SORT_ASC, $parts); // you can use this for ASC order
echo "<pre>";
print_r($parts); //return like this "delicious cake I a o"
?>
Sign up to request clarification or add additional context in comments.

10 Comments

just did some testing and actually this code doesn't produce correct output
@BarneyChambers ok give me some time i will find other solution
But still may be OP not get desired result because he want to sort by index but your solution will sort by value. check your solution with different characters
I believe this still does not work sorry! it appears not to always sort by length correctly
@BarneyChambers please provide me string that causing issue.
|
0

For sorting with length then index you can use array_multisort like below

<?php

$str="I love to code";
$parts=explode(" ", $str);

$keys = array_keys($parts);
$values = array_values($parts);

array_multisort(array_map('strlen', $values), SORT_ASC, $keys, SORT_ASC, $parts);

$new_str = implode(" ", $parts);
echo $new_str;

demo : https://3v4l.org/BJ1Cl

Comments

-1

You may be able to use uasort instead of usort.

From the documentation:

uasort — Sort an array with a user-defined comparison function and maintain index association

The normal usort function does not do this:

If two members compare as equal, their relative order in the sorted array is undefined.

1 Comment

Sorry xander I dont think this will work, I need it to sorts by length and then by array index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.