I would suggest to use method for repeating action. Here is an example and suggest you to handle the case-senitivity of brands/makes.
I would also keep the array index for easy reference.
<?php
class File {
private $_minYear = 2000,
$_maxYear = 2018,
$_brand = array('BMW','Audi','Toyota','Ford');
private function validateYear($year) {
$year = (int)$year;
return ($this->_minYear < $year && $year < $this->_maxYear);
}
public function scan($file) {
$lines = file($file);
foreach ($lines as $key => $value) {
$data = explode(',',$value);
if (in_array($data[0], $this->_brand) && $this->validateYear($data[1])) {
$records[$key] = $value;
} else {
$errors[$key] = $value;
}
}
return array('records' => $records, 'errors' => $errors);
}
}
$file = new File;
$data = $file->scan('testcar.txt');
echo '<pre>';
print_r($data['records']);
print_r($data['errors']);
OUTPUT:
Array
(
[0] => Audi, 2006
[2] => Toyota, 2016
)
Array
(
[1] => BMW, 2019
[3] => Frd, 2017
)
Without using Class/Method
<?php
$brands = array('BMW','Audi','Toyota','Ford');
function validateYear($year) {
$year = (int)$year;
return (2000 < $year && $year < 2018);
}
function fileScan($file) {
$lines = file($file);
foreach ($lines as $key => $value) {
$data = explode(',',$value);
if (in_array($data[0], $brands) && validateYear($data[1])) {
$records[$key] = $value;
} else {
$errors[$key] = $value;
}
}
return array('records' => $records, 'errors' => $errors);
}
$data = fileScan('testcar.txt');
echo '<pre>';
print_r($data['records']);
print_r($data['errors']);