3

I'm writing customized sort function. Current (non-working) code looks like this:

<?php
 function sort_by_key($array, $key) {

   function custom_compare ($a, $b) {
     if ($a[$key][0] > $b[$key][0]) { return 1; }
     else { return -1; }
     }
  return usort($array, "custom_compare");
 }
?>

The problem is that I cannot pass $key variable to custom_compare function. I'd like to avoid using global variables (ugly coding).

1
  • With further reading I noticed that PHP doesn't support nested functions. My code returns error when run second time, PHP tries to re-declarate custom_compare -function. Is there any other options than global variables. I cannot pass more arguments to custom_compare because it is used by usort. Commented Sep 17, 2016 at 10:48

1 Answer 1

5

Untested, but you could use an anonymous function:

<?php
 function sort_by_key($array, $key) {

   $custom_compare = function ($a, $b) use ($key) {
     if ($a[$key][0] > $b[$key][0]) { return 1; }
     else { return -1; }
     };

  return usort($array, $custom_compare);
 }

Based on a small modification of your existing function.

Further your function still needs a small change:

<?php
function sort_by_key(&$array, $key) {
    $custom_compare = function ($a, $b) use ($key) {
        if ($a[$key][0] > $b[$key][0]) {
            return 1;
        } else {
            return -1;
        }
    };

    usort($array, $custom_compare);
}

$array = array(
    array(
        'foo' => array(
            2
        )
    ),
    array(
        'foo' => array(
            3
        )
    ),
    array(
        'foo' => array(
            1
        )
    )
);

sort_by_key($array, 'foo');
var_export($array);

Output:

array (
  0 => 
  array (
    'foo' => 
    array (
      0 => 1,
    ),
  ),
  1 => 
  array (
    'foo' => 
    array (
      0 => 2,
    ),
  ),
  2 => 
  array (
    'foo' => 
    array (
      0 => 3,
    ),
  ),
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply, but that doesn't work. Gives following error instead: PHP Parse error: syntax error, unexpected 'use' (T_USE), expecting '{'
Sorry.... My bad... A stupid error, I did function custom_compare($a, $b) use ($key), not $custom_compare = function($a, $b) use ($key)

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.