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.
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.
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 />"; } ?>
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.
Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With