How to sort a string in PHP. Is there any inbuilt function available in PHP to sort string directly. PHP does not provide any inbuilt function to sort a string directly.
In this post, I’ll show you some of the methods through which we can perform sorting on a string.
How to Sort a String in PHP
Method 1 : Convert String into an Array and Perform Sorting
In this example, we first convert a string into an array. After that, we sort the array and implode them to make a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* Unsorted string needs to be sorted. */ $str = 'qwertyuioplkjhgfdsazxcvbnm'; /* Using str_split convert them into array. */ $sort = str_split($str); /* Sort the array using sort() method. */ sort($sort); /* Implode the sorted array. */ $sort = implode($sort); /* Output will be sorted string. abcdefghijklmnopqrstuvwxyz */ echo $sort; |
Method 2 : Swap the Position of a String
In this example, We use recursive approach to sort a string using swapping the position of a character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* Create a function and take three arguments @str string needs to be sorted @len length of the string @currpos current position, initially it is zero */ function sortStr(&$str, $len, $currpos=0) { if($currpos == $len) return; /* Initialize next var */ $next = $currpos + 1; while($next < $len){ /* Logic of swapping the position of character. */ if($str[$next] < $str[$currpos]){ $temp = $str[$next]; $str[$next] = $str[$currpos]; $str[$currpos] = $temp; } $next++; } /* Recursively call sortStr method, with increment currpos. */ sortStr($str, $len, $currpos+1); } $str = 'jhjabcdewyxdef'; sortStr($str,strlen($str)); /* Output : abcddeefhjjwxy */ echo $str; |
Method 3: Sort string using QuickSort Algorithm
In this method we use QuickSort algorithm to sort a string in-place.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function sortStr($str) { $left = $right = ''; /* Calculation length. */ $len = strlen($str)-1 ; /* if length is less than or equal to zero. */ if ($len <= 0) return $str; /* Let's take middle element as pivot. */ $pivot = floor($len/2); do { if ($len == $pivot) continue; if ($str[$len] <= $str[$pivot]) { $left .= $str[$len]; } else { $right .= $str[$len]; } } while (--$len); return sortStr($left).$str[$pivot].sortStr($right); } $a = sortStr('jhjabcdewyxdef'); echo $a; |