1

I can not get this PHP array to return any values for me. The CSV sheet consists of 10 numbers. The only output I get is "array"

$data = array();
if (($handle = fopen("fullbox.csv", "r")) !== FALSE) {
    while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = $row;
    }
}

echo $data[1];

Any help would be greatly appreciated.

1
  • array is returned as $data[1] is an array try using var_dump() on it Commented Jul 12, 2012 at 15:34

3 Answers 3

3

Your code is already correct.

$data is multidimensional array, each element is an array itself. When you echo $data[1] you are asking PHP to write a string representation of a more complex array variable, which PHP handles by outputting array instead of its contents.

Instead, var_dump() it to see what it contains.

var_dump($data);

A single value would be accessed via something like :

echo $data[1][0];

Edit after comment:

If the CSV contains only one value per row, access it directly via $row[0] when appending to the output array in order to get it as a 1D array:

if (($handle = fopen("fullbox.csv", "r")) !== FALSE) {
  while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $data[] = $row[0];
  }
}
// $data is now a 1D array.
var_dump($data);
Sign up to request clarification or add additional context in comments.

7 Comments

@Micheal Is there a way to setup the array so it would be one dimensional for ease of use. Since I have only one set in the csv file. Thanks
@Djacksway See addition above.
@Micheal maybe I am missing something my CSV consists of one column with 10 numbers. I just want to be able to call whatever number I want by its corresponding position in the array. I tried your previous code and I dont get it to return anything. Thanks for your time.
@Djacksway O assumed you meant one row with ten numbers. Stay tuned for an update.
@Djacksway Code changed above.
|
0

Thats because $data[1] is an array of the 10 numbers in the CSV row, so $data is now a multi-dimensional array. echo $data[1][0] will output one of the numbers

Comments

0

$data[1] is the second element in your $data variable ($data[0] would be the first).

You are getting an array back instead of a value which is why PHP is echoing the word array.

This should work better.

$data[0][0]

Your $data variable is a multidimensional array and you are only going one level deep.

Comments

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.