In JavaScript an array can be sorted depending on the position of a string in each element, using something like this:
arr = arr.sort(function (a, b) {
return a.indexOf(str) - b.indexOf(str);
});
Can a similar thing be done to PHP array, so that it is sorted depending on the position of string in each element?
Yes, you will have to do pretty much the same thing using usort and strpos. Anonymous functions will work as well.
usort($arr, function($a, $b) use ($str) {return strpos($a, $str) - strpos($b, $str)}) //code is not tested, though should work
$str
is the string you are searching for and $arr
is your array
NOTE: use
will only work in PHP 5.3+
I hope this will be helpful for those who will come. I propose an improvement to @DannyPhantom answer.
Any value which doesn't contains the searched string, will be put at first place. strpos
returns false
when the searched string is not found, thus it needs to be handled, because as we all (should) know, false == 0
and strpos()
returns 0 when the searched string is found at the beginning.
As the PHPDoc says
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So, here is my solution
usort($arr, function($a, $b) use ($str) {
$idx_a = strpos($a, $str) === false ? PHP_INT_MAX : strpos($a, $str);
$idx_b = strpos($b, $str) === false ? PHP_INT_MAX : strpos($b, $str);
return $idx_a - $idx_b;
});