Skip to content

Instantly share code, notes, and snippets.

@ProjectOrangeBox
Created April 22, 2021 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProjectOrangeBox/ec329e77dbcc9f3f5d9f31856abcccfd to your computer and use it in GitHub Desktop.
Save ProjectOrangeBox/ec329e77dbcc9f3f5d9f31856abcccfd to your computer and use it in GitHub Desktop.
CSV Functions
<?php
function table(string $filename): array
{
$fp = fopen($filename, 'r');
if ($fp === false) {
die('could not open file' . chr(10));
}
$headers = clean(fgetcsv($fp));
$rows = [];
while (($row = fgetcsv($fp)) !== FALSE) {
$rows[] = array_combine($headers, clean($row));
}
fclose($fp);
return $rows;
}
function clean(array $row): array
{
foreach ($row as $idx => $column) {
$row[$idx] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $column);
}
return $row;
}
function find(array $table, string $columnName, string $value): array
{
foreach ($table as $row) {
if ($row[$columnName] == $value) {
return $row;
}
}
return [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment