0

I'm a newbie and I have a very basic question about PHP arrays

Code:

 While(!feof($file_handle))
  { 
     $SecondRow = fgets($file_handle); //gets row
     $trimmed = trim($SecondRow); //removes extra bits
     $replace = array("'"); 
     $finalstring = str_replace($replace, "_", $trimmed); //Still a string w/o "'"'s

     $CleanString = preg_split("/[\s]*[,][\s]*/", $finalstring); //creates the array

     //print_r($CleanString);    
     echo "Row " . $CleanString[1]. "<br/>"; //??????
   .....
 }//end while

the opened file has the following:

0001,sparta 
0005,PURCHASING

... ... ...

Question: When I echo "Row " . $array[0], I get the first column as expected. But when I echo "Row " . $array[1], I get an the "Undefined offset: 1" error. When the string is read into the array (via preg_split) aren't both array[0]->0001 and array[1]->sparta set?

thanks.

7
  • 3
    why don't you use explode(',', $finalstring) ? Commented Oct 21, 2011 at 17:28
  • 1
    are you just trying to get each column value into an array? Commented Oct 21, 2011 at 17:29
  • 4
    instead of echoing why don't you do a print_r() or a var_dump() to let you know exactly what $CleanString contains? These two functions are very useful for debugging purposes. Commented Oct 21, 2011 at 17:31
  • I tried explode(',', $finalstring) and rec'd the same result. My trying to break the string into an array so i can insert into a mysql database. I'm i bit confused as to why [o] is as intended, but [1] is not Commented Oct 21, 2011 at 17:41
  • Your example works for me. Show me how do you open the file? Commented Oct 21, 2011 at 17:52

2 Answers 2

3

Looking at your entire code, you're essentially replicating a native function like fgetcsv() or one of it's equivalents.

Just pick one and be done :)

As far as determining how to use the array, as noted in the comments use print_r or var_dump() to guide you. Also read up on PHP Arrays

Sign up to request clarification or add additional context in comments.

4 Comments

Hi,explode(',', $finalstring)
ah.. i'll take a look at this function. any ideas as to why [1] is giving an error?
Thanks for the fgetcsv. Much simpler to use
Indeed. If it's what you went with, mark this as the answer by clicking the checkmark. Welcome to StackOverflow.
-1

This is because fgets() get one row at time (one row per "loop").

3 Comments

What does that have anything to do with how many/few pieces each line splits into?
He says "echo "Row " . $array[0]" so I posted why he don't get array[1]. I see now that he really asked about columns, not rows.
correct. Sorry for the confusion. I understand fgets, just a bit confused b.c [1] is giving an error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.