Using PHP to pull one value out of a CSV

This took me much longer to figure out than it should have. I'm such a n00b ;)

Here's the problem I needed to solve: We have a CSV file that we are using to map a specific ID to a page/path in a web site. The CSV has three columns: an ID, a path, and some comments (often left blank). I needed to grab the path corresponding to a given ID.

The solution turned out to be simple, but I thought it might be worth sharing anyway, since I kept getting sidetracked diving down rabbit holes while following things like regular expressions and deprecated functions. Honestly, most people out there are trying to do way more complicated things than I am!

First, we need to be able to pull a single line out of the CSV file:

// Given:

$id = 57;
$fileName = 'test.csv';

// Find the corresponding line in the CSV file

// First, decide what we're looking for. In this case, I want to match the whole first column, so I'm looking for the ID ($id) followed immediately by a comma.
$find = $id . ",";

// Now open the CSV file
$file = new SplFileObject($fileName);

// Set our variable to FALSE, which gives us a way to check for no results on the far side
$grabbed = FALSE;

// And run through the file, checking for the matching line
foreach($file as $line) {
    if(strpos($line, $find) === 0) {
        $grabbed = $line;

Now, every time the foreach finds a matching line, the $grabbed variable will be overwritten. However, the intention of our CSV file is that the ID column contains unique values, so only one line should match. If we end up pulling the wrong value at some point down the road, it means our data is wrong.

Once we have our line, we can extract the value from the second column in that line:

// First we create an array of strings, each a section of the $grabbed line as divided by the commas from the CSV
$strings = explode(',', $grabbed);

// Then, assign the value of the second item in the array to a new variable (remember that arrays count from 0, so the second value is 1)
$Path = $strings[1];