Re: Question - foreach.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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,
Shreyas

Shreyas:

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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux