0

I would like to transform the code below in a function

function filter($row){return ($row['id_menu'] == 10);}

$matches = array_filter($array_mostrar_privilegios, "filter");
foreach ($matches as $element)
{
    echo $element['consultar'];
}

like

function filter($row, $num)
{
    return ($row['id_menu'] == $num);
}
function find($my_array, $num)
{
    $matches = array_filter($my_array, "filter($row, $num)");
    foreach ($matches as $element)
    {
        return $element['consultar'];
    }
}

but i don't how to make it work

2
  • filter doesn't call find, and find doesn't call filter. I don't understand what you're trying to achieve. Commented Mar 6, 2014 at 17:30
  • @hd.: The 2nd parameter to array_filter is a callback. He wants to call filter with an extra parameter. Commented Mar 6, 2014 at 17:31

2 Answers 2

2

If you have PHP 5.3+, then there is no need to use a string as the callback parameter. PHP 5.3+ has anonymous functions.

$matches = array_filter($my_array, function($row) use($num){
    return filter($row, $num);
});

If you do not have PHP 5.3, then you can use create_function (warning: this uses eval()):

$matches = array_filter($my_array, create_function('$row', 'return filter($row,'.$num.');'));
Sign up to request clarification or add additional context in comments.

5 Comments

it returns the follow error: "Parse error: syntax error, unexpected T_FUNCTION"
That means you have PHP 5.2 or below.
@user3249927: Your options are (in the order of preference): 1) Upgrade to a more recent PHP version, 2) Define the function outside (as you're currently doing), 3) Use create_function().
@user3249927: Try the 2nd example I've added to the answer. I would consider upgrading PHP, but if you can't then create_function should work.
I'will try to update later and try your first option before. Thanks for the advice
2

Using closures:

function find($my_array, $num)
{
    $matches = array_filter(
        $my_array, 
        function filter($row) use($num) {
            return ($row['id_menu'] == $num);
        }
    );
    foreach ($matches as $element)
    {
        return $element['consultar'];
    }
}

except that your return inside the foreach will only return the first element from $matches

If you expect multiple $matches values, and want to return them all, consider using yield to turn this into a generator

3 Comments

i had to remove the "filter" to work.. and it return a error to me "Parse error: syntax error, unexpected T_FUNCTION"
@user3249927: If you only need the first result, why do you need a loop? Just print the first result: $matches[0]['consultar'].
i really need like this, coz i have a lot of lines on this array. Thanks for helping

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.