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;
}
array_map()
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);
}