Jump to content

iterating through array while passing an index


johnmerlino

Recommended Posts

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

$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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.