Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to add multiple filters from inside a foreach loop. Unfortunately I can't get the code to reference the value properly. How do I pass the value from the loop to the function?

The following sets all the filters to null.

foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function( $value ) { return $value; } );
}

This is my test code and this sets the filters to 'true'.

foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function( $value ) { return 'true'; } );
}
share|improve this question

closed as off topic by EAMann Jul 24 '12 at 23:41

Questions on WordPress Development Stack Exchange are expected to relate to WordPress within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

    
True, your use case is WordPress ... but this is a vanilla PHP loop/closure question. Closing as off-topic, but not migrating since you've already got an answer. –  EAMann Jul 24 '12 at 23:41
    
Well I didn't know that when I asked it. Far as I knew, my issue could have revolved around my usage of add_filter. –  jnthnclrk Jul 25 '12 at 23:55

1 Answer 1

up vote 2 down vote accepted
foreach ( $myarray as $key => $value ) {
     add_filter( "plugin_filter_$key", function () use ( $value ) { return $value; } );
}

Check out the use keyword for closures.

share|improve this answer
    
Perfect!!!!!!!!! –  jnthnclrk Jul 24 '12 at 18:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.