0

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?

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

0

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+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.