In the follow code:
$numbers=array(1,2,3,4,5);
foreach ($numbers as number) {
...
}
Inside foreach, could i know if i am in the last element of the array
$numbers?
--
João Cândido de Souza Neto
Curitiba Online
jo...@curitibaonline.com.br
(41) 3324-2294 (41) 9985-6894
http://www.curitibaonline.com.br
$last = end ( $numbers );
reset ( $numbers );
foreach ( $numbers as $number ) {
if ( $number == $last ) {
// last element
...
}
....
}
--
John C. Nichel IV
Programmer/System Admin (ÜberGeek)
Dot Com Holdings of Buffalo
716.856.9675
jni...@dotcomholdingsofbuffalo.com
Well, corn my fritters, according to TFM, it does this indeed. Maybe an
old dog can learn new tricks. ;)
I thought foreach() already performed a reset()? Why do it again here?
thnx,
Chris
But in my real code it´s better to use foreach.
Thanks for your tip.
--
João Cândido de Souza Neto
Curitiba Online
jo...@curitibaonline.com.br
(41) 3324-2294 (41) 9985-6894
http://www.curitibaonline.com.br
"Brad Bonkoski" <bbon...@mediaguide.com> escreveu na mensagem
news:452BE40...@mediaguide.com...
In general, you can't.
If the elements are unique, you could do:
$last = end($numbers);
...
if ($last == $number) "this is the end";
Most people who want this "feature" are trying to suppress outputting
a comma or other separator after the last item because they have not
yet figured out how to use this function:
http://php.net/implode
--
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?
> Chris Boget wrote:
>>> $last = end ( $numbers );
>>> reset ( $numbers );
>>
>> I thought foreach() already performed a reset()? Why do it again here?
>>
>
> Well, corn my fritters, according to TFM, it does this indeed. Maybe an
> old dog can learn new tricks. ;)
Actually, foreach() creates a copy of the mentioned array, and the array
pointer of the original array is not modified. Very useful to know if you
append entries to the array you're foreach()-ing and pulling your hair out
why foreach() doesn't iterate through those new entries...
An way of going through the array independent of the actual values (since
using end() relies on unique values):
$n = count($numbers);
$i = 0;
foreach ($numbers as $number) {
$i ++;
if ($i == $n) {
// Last element...
} else {
// Not the last element...
}
}
Ivo
""Richard Lynch"" <c...@l-i-e.com> escreveu na mensagem
news:11949.208.195.234.25...@www.l-i-e.com...
you've already had a few alternatives; how about this:
foreach ($numbers as $key => $number) {
// loopy stuff
}
// do something special with the last item (and it's key?)
// which will currently be stored in $number and $key respectively
// e.g. :
processWhateverTheLastElementWas($numbers[ $key ]);
// or :
processWhateverTheLastElementsValueWas($number);
basically immediately after the foreach loop you have the key and value
of the last element - chances are you therefore have what you need to do what you need. no?
>