1

I am trying to sort an array "$refs" by comparing it to a string "$term" using uasort and regex :

this is my array :

Array
(
    [0] => Array
        (
            [id] => 71063
            [uniqid] => A12171063
            [label] => Pratique...
        )

    [1] => Array
        (
            [id] => 71067
            [uniqid] => A12171067
            [label] => Etre....
        )
...

and my code :

uasort($refs, function ($a, $b) use ($term) {
            $patern='/^' . $term . '/';  

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label']) )== 0) {
                return 0;
            }

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == 1) {
                return -1;
            }
            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == -1) {
                return 1;
            }
        });

I have only 0 like returns, where is my mistake !:/ Thanks

6
  • $refs = $a = $b = $term = ??? Commented Jun 10, 2013 at 17:06
  • $refs is the array, and $term is the word to compare to Commented Jun 10, 2013 at 17:08
  • This is like a 1-liner in perl.. I can write something in Perl if that'd help Commented Jun 10, 2013 at 17:12
  • yes, why not , i'll take it as example . Thanks Commented Jun 10, 2013 at 17:14
  • Works fine here. What's in the $term, I wonder? If it contains regex metacharacters, you probably need to preg_quote it. Commented Jun 10, 2013 at 17:17

1 Answer 1

3

Won't answer the question as stated but you could use this. It will effectively rank the results based on how close the term is to the beginning of the string.

function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
}

This will only work if all of the values have the term somewhere in them (like the results of a like query).

Test script:

$arr = array("aaTest", "aTest", "AAATest", "Test");
$term = "Test";
uasort($arr, function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
});

print_r($arr);

Test Output:

Array
(
    [3] => Test
    [1] => aTest
    [0] => aaTest
    [2] => AAATest
)

UPDATE

Changed code to use stripos instead of strpos for case insensitive sorting

Sign up to request clarification or add additional context in comments.

1 Comment

but i need theme to be at the begining !

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.