Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.