Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to sort values of an array in alphabetical order?

I want to sort values of an array in alphabetical order in PHP. If all values started with same character then they should be sorted using second character and so on. Ignore case sensitive.

For Example:

before:
values[0] = "programming";
values[1] = "Stackoverflow";
values[2] = "question";
values[3] = "answers";
values[4] = "AA Systems";

after:
values[0] = "AA Systems";
values[1] = "answers";
values[2] = "programming";
values[3] = "question";
values[4] = "Stackoverflow";

I have found some algorithms but I want a way that is fast and with small number of statements. Ignoring case sensitive is special for me. Thanks.

like image 462
Naveed Avatar asked Jan 17 '10 07:01

Naveed


People also ask

How do I sort an array alphabetically in PHP?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.

How can we sort an array without using sort method in PHP?

php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>

How do you sort an array of objects in PHP?

The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

How do you sort values in an array?

Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.


1 Answers

You can use uasort(): http://php.net/manual/en/function.uasort.php

uasort( $arr, 'strcasecmp' );

The second argument is a function, which compares values. The function must return -1, 0, or 1. Here's a template, which you can use for your custom functions.

function cmp( $a, $b ) {
  if ( $a == $b ) return 0;
  elseif ( $a > $b ) return 1;
  elseif ( $a < $b ) return -1;
}

uasort( $arr, 'cmp' );

After sorting you might want to reset array indexes.

$arr = array_values( $arr );
like image 111
Arsen K. Avatar answered Nov 04 '22 12:11

Arsen K.