CodeIgniter Forums
get current array position pointer while doing foreach $object->result_array() - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: get current array position pointer while doing foreach $object->result_array() (/showthread.php?tid=32765)



get current array position pointer while doing foreach $object->result_array() - El Forum - 08-04-2010

[eluser]jayapalchandran[/eluser]
Hi,
consider this, a case.
foreach($object->result_array() as $rs)
{
//how do i display the current array element index that is the iteration index.
//i want to call a function when the iterator is in the last-1 position.
// and more specifically i want to use it in this place and not any other for(;Wink loops.
// and even it is an example with other loops then that is fine.
}

There should be an option or by using current() function.
I had tried but still i have to do some analysis...
Instead of debugging and tracing the array elements i am posting this thread.


get current array position pointer while doing foreach $object->result_array() - El Forum - 08-04-2010

[eluser]mddd[/eluser]
Code:
$list = $object->result_array();
$length = sizeof($list);
foreach($list as $key=>$value)
{
  if ($key==$length-1) echo 'This is the last item';
  if ($key==$length-2) echo 'This is the item before the last item';
}



get current array position pointer while doing foreach $object->result_array() - El Forum - 08-04-2010

[eluser]jayapalchandran[/eluser]
Excellent.
Thank you.