concept foreach in category php

appears as: foreach, foreach
Zend Framework in Action

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 ); } }

There are four main looping constructs: while, do-while, for, and foreach. They all allow for a statement or block to be executed a number of times. We’ll start with the while loop.

Using foreach()

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.

Listing A.8. The foreach() syntax

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: