concept foreach in category php
appears as: foreach, foreach

This is an excerpt from Manning's book Zend Framework in Action.
The fetchLatest() function returns a Zend_Db_Table_Rowset, which can be iterated over using the foreach() construct in our view script. In listing 3.10. we assign it to the view within indexAction().
Listing 10.14. Adding read mail functionality to our Support class
public function readMail(Zend_Mail_Storage_Abstract $mail) { foreach ($mail as $messageNum => $message) { $part = $message; while ($part->isMultipart()) { $part = $message->getPart(1); } if (strtok($part->contentType, ';') == 'text/plain') { $plainTextContent = $part->getContent(); } $data['priority'] = isset( $message->xPriority) ? $message->xPriority : 3; $data['status'] = 'open'; $data['title'] = $message->subject; $data['body'] = $plainTextContent; $data['reported_by'] = $message->from; $id = $this->saveIssue($data); $messageString = ''; foreach ($message->getHeaders() as $name => $value) { $messageString .= $name . ': ' . $value . "\n"; } $messageString .= "\n" . $message->getContent(); file_put_contents(getcwd() . '/support/' . $id . '/email.txt', $messageString ); } }
The foreach loop only works with arrays and objects. It iterates over each element in the array and executes a block of statements for each one in turn. This is shown in listing A.8.
Each time through the foreach loop, the value of the current element is assigned to $value and the key to $key. The code in listing A.8 would produce the following output: