Premkumar Ashok chalmeti Premkumar Ashok chalmeti - 3 years ago 167
PHP Question

I am reading csv file and what array_map() function does in this function?

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)
$header = array_map('trim', $row);
$data[] = array_combine($header, $row);
$data[] = $row;
return $data;

and I am bit confused about
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!

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download