0

I basically have a PHP function that is in a giant foreach statement and needs to be in that foreach because it uses values from the loop.

foreach ($x as $y) {

...

            function sortq($a, $b){
                if ((int)$a->id == (int)$b->id) {
                    return 0;
                }
                return ((int)$a->id < (int)$b->id) ? -1 : 1;
            }

            usort($sort, 'sortq');

...

}

How do I strip this function out into a generic class or method so that I can call it any number of times? I attempted the 'class' route but was then redeclaring classes in the foreach loop :D

Please help! Many thanks

Tim
  • 6,986
  • 8
  • 38
  • 57

1 Answers1

1

Wrapping the function definition in a function_exists check will work:

if (!function_exists('sortq')) {
    function sortq($a, $b) { ... }
}

If you can depend on having at least PHP 5.3+, you should use a closure:

usort($sort, function($a, $b) {
    if ((int)$a->id == (int)$b->id) {
        return 0;
    }
    return ((int)$a->id < (int)$b->id) ? -1 : 1;
});

Edit: Actually, the definition of the comparison function required by usort says:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

So you can simplify that function to just:

function ($a, $b) { return (int)$a->id - (int)$b->id; }
Boann
  • 48,794
  • 16
  • 117
  • 146