Sorting an array / a variable by first letter in PHP

How can you sort the following word by the given rule?

Example data is saapas which I want to be either

aaapss

or in the array

s
a
a
p
a
s

and then somehow

a
a
a
p
s
s

The function arsort with sort_flags SORT_REQULAR and SORT_STRING did not work for me.

Upvotes: 1

Views: 4987

Answers (3)

jay
jay

Reputation: 10325

In your original post you said either a string or an array. eyze's solution works for the string but sort() will work for the array of values:

$array = array('s', 'a', 'a', 'p', 'a', 's');
sort($array);

//will output
Array
(
    [0] => a
    [1] => a
    [2] => a
    [3] => p
    [4] => s
    [5] => s
)

Upvotes: 1

Alix Axel
Alix Axel

Reputation: 154701

$string = 'saapas';
$string = str_split($string, 1);
sort($string);
echo implode('', $string);

Upvotes: 2

powtac
powtac

Reputation: 41080

$string = 'saapas';
echo implode(sort(str_split($string, 1)));

Upvotes: -1

Related Questions