Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
array is returned as $data[1] is an array try using var_dump() on it – Nicholas King Jul 12 '12 at 15:34

3 Answers

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);
share|improve this answer
@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 Jul 12 '12 at 15:42
@Djacksway See addition above. – Michael Berkowski Jul 12 '12 at 15:44
@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 Jul 12 '12 at 15:50
@Djacksway O assumed you meant one row with ten numbers. Stay tuned for an update. – Michael Berkowski Jul 12 '12 at 15:56
@Djacksway Code changed above. – Michael Berkowski Jul 12 '12 at 15:58
show 3 more comments

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

share|improve this answer

$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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.