johnmerlino Posted June 25, 2011 Share Posted June 25, 2011 Hey all, the foreach loop allows you to iterate through an array and pass an index: foreach($array as $key=>$value) { // $value is the current item in array and $key is index } I want to do the same thing but add the functionality as part of my Enumerator class: class Enumerator { public $arr; public function __construct($array=array()) { $this->arr = $array; } public function each($lambda) { array_walk($this->arr, $lambda); } } So for example now I can do this: $elements = new Enumerator(array('email','fax','phone','postal mail')); $elements->each(function($l){ echo form_checkbox("checked[]",$l); }); But I may want to do this: $elements = new Enumerator(array('email','fax','phone','postal mail')); $elements->each_with_index(function($l,$i){ if($i % 2 == 0){ echo form_checkbox("checked[]",$l); echo "</br>; } else{ echo form_checkbox("checked[]",$l); } }); thanks for response Quote Link to comment https://forums.phpfreaks.com/topic/240402-iterating-through-array-while-passing-an-index/ Share on other sites More sharing options...
ignace Posted June 26, 2011 Share Posted June 26, 2011 $elements = new Enumerator(array('email','fax','phone','postal mail')); $elements->each(function($l, $i){ echo form_checkbox("checked[]",$l); if (!($i % 2)) echo "<br>"; }); have you tried this? Also take a look at the php manual page for array_walk as you'll see that it passes 2 parameters. Quote Link to comment https://forums.phpfreaks.com/topic/240402-iterating-through-array-while-passing-an-index/#findComment-1234920 Share on other sites More sharing options...
johnmerlino Posted June 27, 2011 Author Share Posted June 27, 2011 thanks for response Quote Link to comment https://forums.phpfreaks.com/topic/240402-iterating-through-array-while-passing-an-index/#findComment-1235213 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.