Jump to content


Returning A Variable One Element At A Time

  • Please log in to reply
3 replies to this topic

#1 Jimbo_17

  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 22 June 2006 - 04:11 PM

I am trying to return an array, but only one element at a time. Much in the same way that mysql_fetch_array does. Here is an example of what I am trying to do.

class test {
  public function one(){
    $test = array(1,2,3,4,5);
    foreach($test as $array){
      return $array;

$TEST = new test();
while($blah = $TEST->one()){
  print $blah;  //Want this to print out only one element at a time

Thanks in advance!

#2 Buyocat

  • Members
  • PipPipPip
  • Advanced Member
  • 267 posts

Posted 22 June 2006 - 04:50 PM

When you say return, could you be more specific? Because the return command in a method can only be called once, as the method is exited as soon as something is returned. So if you want to interate through an array or something one at at time, returning a value each time. You'll either want to create a special iterator class that can remember its place in the array, or you'll just want a simple foreach loop that goes through the array one at a time letting you do stuff.

EDIT - after looking at your example you want to create an interator

I'll let you devise an iterator class, it would need an attribute like $myPlace and would probably want some methods like, hasNext, next etc. Then you would call the method and next and it would return the next value in the array or whatever and increment the $myPlace value.
Looking for some easy-to-use tools?  Try these, https://sourceforge....jects/utils-php -- I made them myself.  They're distinct tools which are easy to understand and use.  See some examples uses at http://www.anotherearlymorning.com

#3 Jimbo_17

  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 22 June 2006 - 05:00 PM

Thank you for the quick reply! I am trying to write a class that can treat a comma seperated values file (CSV) like a database. The problem I am running into is I want to have a function iterate through the file and grab the fields from one line at a time and spit them out. I need a way to grab the fields from one line, store them outside the class, and then go get the next line and start it all over.

CSV Example:

Bob,555-5555,32 Foo Street
Shirley,555-5555,RM 354 Barr Apts

I want the function to grab Bob's info, split it into an array, and then pass the array out of the class. Once the array is out of the class (In other words, in my index.php), I want it to get Shirley's info and do the same thing.

#4 kenrbnsn

  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 23 June 2006 - 02:47 AM

You might want to take a look at the function [a href=\"http://www.php.net/fgetcsv\" target=\"_blank\"]fgetcsv()[/a].


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users