Page 1 of 1

Foreach & Array related

Posted: Wed Oct 20, 2004 12:53 pm
by Shendemiar

Code: Select all

<?php
foreach ($result as $key => $value)
{
something here
}
?>
How can i check if i'm on the first element of the loop? (assuming there is more than 0 elements in the array)

Posted: Wed Oct 20, 2004 1:23 pm
by feyd

Code: Select all

$keys = array_keys($result);
foreach($result as $key => $value)
{
  if($key == $keys[0]) // first element?
  {}
  else
  {}
}

Posted: Wed Oct 20, 2004 2:22 pm
by pickle
The foreach loop automatically starts on the first key. It creates and uses it's own pointer in the array, so there's no need (that I can think of - please enlighten me if I'm wrong) to double check if your starting at the beginning.
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.
Manual page: [php_man]foreach[/php_man]

Posted: Wed Oct 20, 2004 2:26 pm
by feyd
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.

Posted: Wed Oct 20, 2004 4:02 pm
by Shendemiar
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.
Yes thats correct. Thanks for the hint.

Posted: Wed Oct 20, 2004 4:59 pm
by Christopher

Code: Select all

$n = 0;
foreach ($result as $key => $value)
{
    if ($n == 0) {
// something on only a specific row
    }
// something here
    ++$n'
}
?>
Or if you only care about the first row:

Code: Select all

$firstrow = true;
foreach ($result as $key => $value)
{
    if ($firstrow) {
// something on only the first row
        $firstrow = false;
    }
// something every row
}
?>
Or for speed:

Code: Select all

$firstvalue = $result[0];
// something on only the first row
unset($result[0]);
foreach ($result as $key => $value)
{
// something every other row
}
?>

Posted: Wed Oct 20, 2004 6:29 pm
by Shendemiar
Heh, thanks. Actually quite handy examples for all-array related looping :D