piznac Posted June 5, 2010 Share Posted June 5, 2010 How can I limit a foreach loop based on the value of an array. I tried something like this and it didn't work: foreach($options as $key => $value) { if($key != 'sortby' || $key != 'sortdirection') { $this->db->where($key,$value); } } This what I'm sending it: array('lad_id' => $ladid, 'sortby' => 'score', 'sortdirection' => 'ASC') I saw that I could do something like this: array_slice($options, 0, 2) However I wont know the numbers, I would like to limit it by the array values. Is there a way to do this? Thank you. Link to comment https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/ Share on other sites More sharing options...
piznac Posted June 5, 2010 Author Share Posted June 5, 2010 array_filter looks like a good option, but I don't understand how to make a callback to show the values. Am I getting closer? lol Link to comment https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/#findComment-1068245 Share on other sites More sharing options...
piznac Posted June 5, 2010 Author Share Posted June 5, 2010 bumpy bump bump? Link to comment https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/#findComment-1068323 Share on other sites More sharing options...
jcbones Posted June 5, 2010 Share Posted June 5, 2010 A callback function for array_walk is built that it takes one argument, and returns either true or false. It is built in the same manner as a regular function, but make sure it has an argument to it. When the array_filter runs, it runs each element of the array against your function. //Is first char a letter? suppose to be a number. function letters($str) { $str = substr($str,0,1); if(!is_numeric($str)) return false; return true; } //make an array; $array = array('me','exercise','another','none','1dies'); //filter the array by our function; $array1 = array_filter($array,'letters'); var_dump($array1); On the other hand, array_walk passes both the key, and the value to a user defined function. As in: function letters($value,$key) { $str = substr($key,0,1); echo $str . ': ' . $value . "<br />\n"; return; } //make an array; $array = array('me' => 'walking', 'fall' => 'exercise', 'taste' => 'another', 'three' => 'none', '14' => '1dies'); //filter the array by our function; array_walk($array,'letters'); PS. don't bump, we see it. Link to comment https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/#findComment-1068325 Share on other sites More sharing options...
piznac Posted June 5, 2010 Author Share Posted June 5, 2010 Ok cool,. Ill check that out,. thanks. Link to comment https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/#findComment-1068327 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.