Reply to comment

Inserting Breaks Into a Stream of Values (turning lists into tables)

A couple years back, I used a technique to simplify code that iterates over an array and displays it as a table.

A typical way to turn this one-dimensional list of values into a two-dimensional table is to nest two FOR loops. So if you have a three column layout, you write one outer loop that goes from 1 to EOF, and inside that, you have a loop that goes from 1 to 3.

That's not a nice way to do it, because 1/3 of the time, you end the loop before the inner loop completes. The code can get ugly.

The way I dealt with it was to get rid of the loop and return to the more primitive iterator pattern. Then, just check if our index happens to land on 3. Here's a class that does it:

class BizBuzz 
{
function BizBuz( $biz, $buz ) 
{
	$this->biz = $biz;
	$this->buz = $buz;
	$this->reset();
}
function reset() { $this->counter = 0; }
function next() {
	$this->counter++;
	$this->isBiz = ( 0 == ($this->biz % $this->counter) );
	$this->isBuz = ( 0 == ($this->buz % $this->counter) );
	return $this->counter;
}
}

That's untested code. The idea is to put the logic right around the increment operation. You can use these flags later in the layout or other parts of the app.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <dd> <dl> <dt> <i> <li> <ol> <u> <ul> <p> <br> <div> <pre> <code> <img><h1><h2><h3><h4> <blockquote>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

.