Background
This article demonstrates how to use the Iterator interface in PHP. Objects implementing this interface works like an array when used in foreach constructs.
[wp_ad_camp_1]
Software Environment
- Windows 7 Professional SP1
- PHP 5.5.9 / Zend Engine v2.5.0
- NetBeans IDE 8.0.1
The Codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | internal_array = $array; } // Get the element indexed by $pointer public function current() { return $this->internal_array[$this->pointer]; } // Get the current index public function key() { return $this->pointer; } // Move index to next available item public function next() { $this->pointer++; } public function rewind() { // n/a } /* This is like the loop condition in your for(;;) statement. * Return false to terminate foreach, return true to continue * the loop */ public function valid() { return $this->pointer < count($this->internal_array); } } $names = ['Mark', 'John', 'Peter']; $my_iterator = new MyArrayIterator($names); foreach($names as $each_name) { echo "$each_name\n"; } echo "\n\n"; foreach($names as $key=>$value) { echo "$key - $value\n"; } |
Sample Output
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 | Mark John Peter 0 - Mark 1 - John 2 - Peter |
Get the Codes
https://github.com/Turreta/php-essentials/blob/master/spl%20libray/Foreach_Array_Iterator_Sample.php
[wp_ad_camp_3]