Foreach & Array related
Posted: Wed Oct 20, 2004 12:53 pm
Code: Select all
<?php
foreach ($result as $key => $value)
{
something here
}
?>A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
<?php
foreach ($result as $key => $value)
{
something here
}
?>Code: Select all
$keys = array_keys($result);
foreach($result as $key => $value)
{
if($key == $keys[0]) // first element?
{}
else
{}
}Manual page: [php_man]foreach[/php_man]PHP Manual wrote: Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Also note that foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.
Yes thats correct. Thanks for the hint.feyd wrote:I think it's more that Shendemiar wants to do some differing or specialized processing on the first element, and not on the following ones.
Code: Select all
$n = 0;
foreach ($result as $key => $value)
{
if ($n == 0) {
// something on only a specific row
}
// something here
++$n'
}
?>Code: Select all
$firstrow = true;
foreach ($result as $key => $value)
{
if ($firstrow) {
// something on only the first row
$firstrow = false;
}
// something every row
}
?>Code: Select all
$firstvalue = $result[0];
// something on only the first row
unset($result[0]);
foreach ($result as $key => $value)
{
// something every other row
}
?>