note 92761 modified in function.array-filter by danbrown

From: Date: Fri, 07 Aug 2009 22:03:58 +0000
Subject: note 92761 modified in function.array-filter by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-159199@lists.php.net to get a copy of this message
Wanting to pass an additional to parameter to the callback function? This worked for me, there's probably another way to accomplish this task but just so you see how it can be done. (I actually used this technique to strip old dates out of an array) : <?php //define in global scope so functions can access $var_to_pass = null; function myfilter($input_var_outer,$param) { global $var_to_pass; $var_to_pass = $param; function mycallback($input_var_inner) { global $var_to_pass; return ($input_var_inner>$var_to_pass) ? true : false; } $return_arr = array_filter($input_var_outer,'mycallback'); //re-key if you want $return_arr = array_merge(array(),$return_arr); return $return_arr; } $min = 5; $a = array(1,3,5,7,9); //remove elements from array that are not greater than $min $a = myfilter($a,$min); echo "<pre>"; print_r($a); echo "</pre>"; ?> -- Output: Array ( [0] => 7 [1] => 9 ) --was-- Wanting to pass an additional to parameter to the callback function? This worked for me, there's probably another way to accomplish this task but just so you see how it can be done. (I actually used this technique to strip old dates out of an array) : //define in global scope so functions can access $var_to_pass = null; function myfilter($input_var_outer,$param) { global $var_to_pass; $var_to_pass = $param; function mycallback($input_var_inner) { global $var_to_pass; return ($input_var_inner>$var_to_pass) ? true : false; } $return_arr = array_filter($input_var_outer,'mycallback'); //re-key if you want $return_arr = array_merge(array(),$return_arr); return $return_arr; } $min = 5; $a = array(1,3,5,7,9); //remove elements from array that are not greater than $min $a = myfilter($a,$min); echo "<pre>"; print_r($a); echo "</pre>"; -- Output: Array ( [0] => 7 [1] => 9 ) http://php.net/manual/en/function.array-filter.php

« previous php.notes (#159199) next »