tags:

views:

77

answers:

1

get current array position pointer while doing foreach $object->result_array()

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(;;) 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.

and above all is it possible to do it with a for loop?

+1  A: 

Add => $key like this to get key as well:

foreach($object->result_array() as $rs => $key)
{
   echo $key;
}

and above all is it possible to do it with a for loop?

Yes like this:

for($i = 0; $i < count($object->result_array()); $i++)
{
  // your code...
}
Sarfraz
Working. Thank you. but...What you have said is right but it seems that you want just point me some idea instead of giving some more of code.anyway i got what i want and i have voted you. thank you.In that code i want $rs which is the current index number that is the array position or the iterator.and in for loop we need to do $object->result_array[$i]['field']It figured out both but you can have given like this.Anyway i tried myself and by this way let us have our analytics sharp.I assumed from your code and made up this.
Jayapal Chandran
Anyway i got what i want and i have voted your answer. thx.
Jayapal Chandran
@Jayapal Chandran: That is good news and I answered as much as i could understand your question. It is good to see that you figured it out remaining part yourself and that is always a good thing for a programmer :)
Sarfraz
yeah.Here is my 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';}
Jayapal Chandran
I wonder how you were able to post immediately.Do you have any api for that and if so then please give me a reference i will too implement it in my side so that i can monitor new questions and answers to my questions.
Jayapal Chandran
Why in comments section we cannot post code?do we have to answer our own question like in the other forums(vbulletin)?
Jayapal Chandran
@Jayapal Chandran: It was general php question not specific to api, you see it was related to a loop. As for comments code and answers, have a look at: http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work
Sarfraz
What i asked was do you have any program to monitor stackover flow to detect latest posts and answers. do you?
Jayapal Chandran