What are some best practices for efficiently accessing and outputting specific values from a text file in PHP using arrays and loops?

When accessing specific values from a text file in PHP using arrays and loops, it is best to read the file line by line, extract the desired values, and store them in an array for easy access. By using loops to iterate through the file contents, you can efficiently extract and output the specific values you need.

$file = fopen("data.txt", "r");
$data = [];

while(!feof($file)) {
    $line = fgets($file);
    $values = explode(",", $line);
    
    // Assuming the values you need are in specific positions
    $specificValue1 = $values[0];
    $specificValue2 = $values[1];
    
    // Store the values in an array for easy access
    $data[] = [
        'specificValue1' => $specificValue1,
        'specificValue2' => $specificValue2
    ];
}

fclose($file);

// Output the specific values
foreach($data as $item) {
    echo $item['specificValue1'] . ", " . $item['specificValue2'] . "\n";
}