2

I'm using usort to sort a multi-dimensional array. It works fine until the key used to sort concatenates a global variable.

var_dump($lang);//OK, outputs 'eng'

function cmp(array $a, array $b) {
    if ($a['name'] < $b['name']) {
        return -1;
    } else if ($a['name'] > $b['name']) {
        return 1;
    } else {
        return 0;
    }
}

function cmp2(array $a, array $b) {
    global $lang;
    var_dump($lang);//null?

    if ($a['name_'.$lang] < $b['name_'.$lang]) {//line: 93
        return -1;
    } else if ($a['name_'.$lang] > $b['name_'.$lang]) {
        return 1;
    } else {
        return 0;
    }
}

usort($platform['Server'], "cmp");//OK
usort($platform['Asset'], "cmp2");//Notice (8): Undefined index: name_ [APP\View\Platforms\view.ctp, line 93]

How can I concatenate the lang variable inside the function passed to usort?

I'm on PHP 5.3.

Also, would there be a way to unify both these functions into one while passing the key to sort on as a parameter?

3
  • What version of PHP are using? If you are using PHP 5.3+, I have a solution for you. Commented May 1, 2014 at 16:30
  • As for this code, my guess is that this code is inside a function, so $lang isn't actually global. Commented May 1, 2014 at 16:31
  • @rocketHazmat We're on 5.3, will look at your solution Commented May 1, 2014 at 16:36

1 Answer 1

11

If you are using PHP 5.3+, then you can take advantage of anonymous functions:

usort($platform['Asset'], function(array $a, array $b) use($lang){
    if ($a['name_'.$lang] < $b['name_'.$lang]) {
        return -1;
    } else if ($a['name_'.$lang] > $b['name_'.$lang]) {
        return 1;
    } else {
        return 0;
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for pointing out how to pass $lang to the function, couldn't figure out how I was going to accomplish this... even though a quick search with specific keywords (just learned) seems to yield the same answer you provided. Ah well...
Here's the docs for it: php.net/manual/en/functions.anonymous.php#example-180 "Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct."
i never knew about use! doh!

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.