note 91921 modified in language.oop5.iterations by danbrown

From: Date: Wed, 01 Jul 2009 17:13:30 +0000
Subject: note 91921 modified in language.oop5.iterations by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157785@lists.php.net to get a copy of this message
This is what seems to work for checking isFirst() and isLast() on a class implementing the Iterator interface - without destroying the internal array pointer: <?php // Let $this->_elements be your internal array with // array("one", "two", "three") public function isFirst() { $hasPrevious = prev($this->_elements); // now undo if ($hasPrevious) { next($this->_elements); } else { reset($this->_elements); } return !$hasPrevious; } public function isLast() { $hasNext = next($this->_elements); // now undo if ($hasNext) { prev($this->_elements); } else { end($this->_elements); } return !$hasNext; } // usage foreach ($myInterator as $value) { echo $value; if ($myInterator->isFirst()) { echo " (first)"; } if ($myInterator->isLast()) { echo " (last)"; } echo " - value is still the same: ", $value, "<br />"; } ?> output: one (first) - value is still the same: one two - value is still the same: two three (last) - value is still the same: three This can be helpfull for designing CSS elements where the first or last element must have a different padding/margin than the others. --was-- This is what seems to work for checking isFirst() and isLast() on a class implementing the Iterator interface - without destroying the internal array pointer: // code: // Let $this->_elements be your internal array with // array("one", "two", "three") public function isFirst() { $hasPrevious = prev($this->_elements); // now undo if ($hasPrevious) { next($this->_elements); } else { reset($this->_elements); } return !$hasPrevious; } public function isLast() { $hasNext = next($this->_elements); // now undo if ($hasNext) { prev($this->_elements); } else { end($this->_elements); } return !$hasNext; } // usage foreach ($myInterator as $value) { echo $value; if ($myInterator->isFirst()) { echo " (first)"; } if ($myInterator->isLast()) { echo " (last)"; } echo " - value is still the same: ", $value, "<br />"; } // output one (first) - value is still the same: one two - value is still the same: two three (last) - value is still the same: three This can be helpfull for designing CSS elements where the first or last element must have a different padding/margin than the others. http://php.net/manual/en/language.oop5.iterations.php

« previous php.notes (#157785) next »