-1

In PHP, I want to read a ".CSV" file using the following function.

function csv_to_array($filename='a.txt',  $header_exist=true, $delimiter="\t")
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if($header_exist)
            {
                if(!$header)
                    $header = array_map('trim', $row);
                else
                    $data[] = array_combine($header, $row);
            }
            else
                $data[] = $row;
        }
        fclose($handle);
    }
    return $data;
}

and I am bit confused about array_map() function. I think it is supposed to map column names to each attribute is that so then how to fetch and display eacg attribute?

Thank you!

Premkumar chalmeti
  • 800
  • 1
  • 8
  • 23

2 Answers2

1

Opening a manual page for array_map you can see that:

array_map — Applies the callback to the elements of the given arrays

So, you have a callback, which is trim (a core php function) and an array, which is $row. So, function trim now applied to each element of $row.

So, it is equivalent of:

$header = [];
foreach ($row as $item) {
    $header[] = trim($item);
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
-1

In PHP, array_map(function_name, array) function sends each value of array to the function_name() and returns a new array.

In your case, The $header holds the string of column names separated by ,'s. This means array_map() function converts them into an array.

Hope you get it.