0

I have been researching fgetcsv() and have the following working code:

$file = fopen($pathToCsv,"r");
$data = array();

while(! feof($file))
  {
      array_push($data, fgetcsv($file));
  }

fclose($file);

However, when I try to adapt this to dynamically accept an unknown number of csv files stored into an array, things cease to work:

$year = $_POST['year'];
$m = "maths".$year;
$sheets = $$m; //an array containing between 5 an 8 paths to csv and other info
$data = array();

function ArrayFromCsv($file, $i) {
    while(! feof($file))
    {
        array_push($data[$i], fgetcsv($file)); //line 15
    } 
    fclose($file);
}



for ($i = 0; $i < count($$m); $i++){
    array_push($data, array());
    $x = fopen($sheets[$i]['csv'],'r');
    ArrayFromCsv($x, $i);
}

I get: Warning: array_push() expects parameter 1 to be array, null given in ... on line 15

I'm not how to research this further. Is there a better way or obvious mistake? I've tried a number of methods.

2

2 Answers 2

1

You dont have access to the global $data variable inside of the function ArrayFromCsv. You either need to use "global $data" inside the function, which is bad, so DON'T Or you could create a temporary array inside the function, which you return when the function ends and put the returned value from the function into $data[$i]. Also you should not open a file outside of a function and close it inside of a function. That could lead to undefined behaviour someday when your code gets bigger.

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

Comments

1
function ArrayFromCsv($file, $i) use (&$data) {
    while(! feof($file))
    {
        array_push($data[$i], fgetcsv($file)); //line 15
    } 
    fclose($file);
}

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.