15ongm 15ongm - 13 days ago 11
PHP Question

Why is the array empty?

I'm trying to convert a csv file into an HTML table. For the first part, I'm trying to load all the time cells from the csv file into a time array, event cells into the event array, and location cells into the location array.

After

fclose($file);
, I did
print_r($time);
and it returned
Array ( [0] => Time )
. But after
get_data($time, $events, $location);
, I did
print_r($time);
and got
Array()
. Why is it blank? How can I load all time cells into the time array, the event cells into the event array, and the location cells into the location array?

EventsScheduleFriday.csv

Time,Event,Location,
12:30pm,Hilby The Skinny German Juggle Boy,West State Street,
4:45pm,Hilby The Skinny German Juggle Boy,West State Street,
6pm,Finger Lakes Comedy Festival Competition 1st Round (Age 21+),Lot 10,
8pm,Stand-up Comedy Show,Acting Out NY,
10pm,All-Star Comedy Show,Acting Out NY


PHP code:

<?php
$time = array();
$events = array();
$location = array();

function get_data($time, $events, $location) {
$file = fopen(__DIR__."/../data/EventsScheduleFriday.csv", "r"); //read .csv file
while(!feof($file)) { //while end of file has not been reached
$content = fgetcsv($file, ","); //converts first line of csv to an array
array_push($time, $content[0]);
array_push($events, $content[1]);
array_push($location, $content[2]);
}
fclose($file); //closes csv file
}

get_data($time, $events, $location);

?>

Answer

Reason this happens if because you use variables that are outside the method scope. When you pass these to the method, they are assigned the correct values from the CSV file, but they are not carried outside the method when the method finishes. This is how PHP treat variables and scopes. What you need to do is pass the variables by reference. Doing this, PHP will carry the assigned values outside the method too.

To do this, you need to change to line:

function get_data($time, $events, $location) {

To:

function get_data(&$time, &$events, &$location) {