0

Pls see my code below, which is meant to validate whether a variable has on of the specific value (and based on solution example of Is it possible to add to filter_var() function user-defined parameters?)

I tested two cases (A, B) as descibed in the comments in the code below. I dont understand why the function is not working properly in case B? (which I tested by means of ideone.com)

function validate_select($val, $myoptions)
{
//print_r($myoptions);
for($i=0;$i<count($myoptions);$i++){
    if($val==$myoptions[$i]){
        return $val;
    }
}
    return false;
}

$testVar = 'apple';
$myoptions = array('banana','pear','apple');
$result = filter_var($testVar, FILTER_CALLBACK, array('options' => function($var) {
  //return validate_select($var, array('banana','pear','apple')); //case A: returns correct value 'apple'
  return validate_select($var, $myoptions); //case B: returns unexpected value false
}));
echo($result);

1 Answer 1

2

$myoptions is outside of your function... try add function ($var) use ($myoptions) like

$result = filter_var($testVar, FILTER_CALLBACK, array('options' => function ($var) use ($myoptions) {
    return validate_select($var, $myoptions);
}));
Sign up to request clarification or add additional context in comments.

1 Comment

thnx. However, that still does not seem to work (returns false in described example) (How does your line of code 'know' to call function validate_select()?

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.