# Iterator Implementation

**URL:** <https://www.phphelp.com/t/iterator-implementation/12641>\
**Category:** General PHP Help\
**Created:** [February 8, 2011, 9:10pm UTC](https://www.phphelp.com/t/iterator-implementation/12641 "2011-02-08T21:10:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://www.phphelp.com/uploads/default/original/2X/2/243e9ed5d93c5653ce3186f18df16e019ce38445.png) [@system](https://www.phphelp.com/u/system)\
**Post date:** [February 8, 2011, 9:10pm UTC](https://www.phphelp.com/t/iterator-implementation/12641/1 "2011-02-08T21:10:58Z")

</div>

Iterator Implementation Task  
Create a Locations class that implements PHP’s Iterator interface. The class will iterate over all rows in a table named `locations` (outlined below) and return the id and name in a key=\>value form. The class must be used as it is in the Usage section below.  
Assumptions  
• A database connection has already been set up for you. Just use mysql\_query for your queries.  
• Data already exists in the table.  
Table Structure  
±--------------------±------------±-----±----±--------±---------------+  
| Field | Type | Null | Key | Default | Extra |  
±--------------------±------------±-----±----±--------±---------------+  
| location\_id | int(11) | NO | PRI | NULL | auto\_increment |  
| location\_name | varchar(32) | YES | | NULL | | ±--------------------±------------±-----±----±--------±---------------+  
Usage  
echo ‘

’; foreach (new Locations as $id =\> $name) {  
printf(’- %s
’, $id, $name); echo ‘
’;  
}

---

<div class="post-metadata">

**Author:** ![Redscouse](https://www.phphelp.com/user_avatar/www.phphelp.com/redscouse/32/124_2.png) [@Redscouse](https://www.phphelp.com/u/Redscouse)\
**Post date:** [February 9, 2011, 12:55pm UTC](https://www.phphelp.com/t/iterator-implementation/12641/2 "2011-02-09T12:55:29Z")

</div>

Hi Jim 😃

I replied to your email and sent the code, but i’ve included it here too:  
[php]class Locations  
{  
function locations()  
{  
$query = “SELECT \* FROM locations ORDER BY location\_id ASC”;  
$result = mysql\_query($query);

```
	while($row = mysql_fetch_array($result, MYSQL_NUM))
	{
		$data[] = array('location_id' => $row[0], 'location_name' => $row[1]);
	}
	return $data;
}

```

}

$x = new Locations;  
$data = $x-\>locations();  
$count = count($data);

echo ‘

’;  
for($i=0; $i\<=$count-1; $i++)  
{  
echo ‘- ’ . $data[$i][‘location\_name’] . ‘
’;  
}  
echo ‘
’;  
[/php]

Goodluck with your course  
😉
