15ongm 15ongm - 1 month ago 22
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.


, I did
and it returned
Array ( [0] => Time )
. But after
get_data($time, $events, $location);
, I did
and got
. 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?


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:

$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);



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) {


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