What potential pitfalls should be avoided when working with arrays in PHP to process data from a text file?
One potential pitfall to avoid when working with arrays in PHP to process data from a text file is not properly handling empty lines or unexpected data formats. To mitigate this, you can check for empty lines or validate the data format before processing it into an array.
$file = fopen('data.txt', 'r');
$data = [];
while (($line = fgets($file)) !== false) {
// Skip empty lines
if(trim($line) == '') {
continue;
}
// Validate data format
if(!preg_match('/^\d+,\w+/', $line)) {
// Handle invalid data format
continue;
}
// Process valid data into array
$parts = explode(',', $line);
$data[] = [
'id' => $parts[0],
'name' => $parts[1]
];
}
fclose($file);
print_r($data);