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 😀
Please help! Many thanks
Wrapping the function definition in a function_exists check will work:
If you can depend on having at least PHP 5.3+, you should use a closure:
Edit: Actually, the definition of the comparison function required by usort says:
So you can simplify that function to just: