Re: Question - foreach.
| From: | tedd | Date: | Thu, 10 Jun 2010 11:03:28 +0000 |
| Subject: | Re: Question - foreach. | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-306004@lists.php.net to get a copy of this message | ||
At 7:19 AM +0530 6/10/10, Shreyas wrote:
PHP'ers, I am reading a PHP book which explains foreach and at the end says : *'When foreach starts walking through an array, it moves the pointer to the beginning of the array. You don't need to reset an array before walking through it with foreach.'* * * *Does this mean - * *1) Before I navigate the array, foreach will bring the pointer to the starting key?* *2) After the first index, it goes to 2nd, 3rd, and nth? * Regards, ShreyasShreyas: This is one of those questions that you can test very easily, just initialize an array and try it. <?php $test = array(a, b, c, d); foreach ($test as $value) { echo("value = $value <br>"); } ?> As the references show, there are two versions of the "foreach", the one above and this: <?php $test = array(a, b, c, d); foreach ($test as $key => $value) { echo("$key= $key value=$value <br>"); } ?> Note that you can pull-out the index (i.e., $key) as well as the value (i.e., $value) of each index. The "<br>" is only to add a linefeed in html. This is a bit easier than using a for() loop. Cheers, tedd -- ------- http://sperling.com http://ancientstones.com http://earthstones.com