[ACCEPTED]-PHP Find String in CSV file-arrays

Accepted answer
Score: 12

As per reko_t's suggestion: Use fgetcsv 4 to read individual lines of csv into arrays, until 3 you find one where the second element matches 2 your search term. The first element then 1 is the username. Something like:

<?php
function find_user($filename, $email) {
    $f = fopen($filename, "r");
    $result = false;
    while ($row = fgetcsv($f)) {
        if ($row[1] == $email) {
            $result = $row[0];
            break;
        }
    }
    fclose($f);
    return $result;
}
Score: 2

You may use fgetcsv() directly

$string = "user_email@something.com";
$filename = "user_email.txt";
$h = fopen("$filename","r");
$flag=0;

while (!feof ($h)) {
    list($username, $email= fgetcsv($h);

    if ($string == $email) { /* do something */ }
}

fgetcsv() (as a nice side effect) also 8 removes the "field enclosures" (the 7 double quotes ") for you, if they exists.

Your 6 own example probably does not work, because 5 if you have such a line

"username", "email"

splitting at , will 4 result in

'"username"'
' "email"'

Notice the whitespace before "email", that 3 you forgot to remove. Additional using str_replace() to 2 remove the surrounding quotes is quite unsafe. Have 1 a look at trim().

Score: 1

First, just use file() to get the contents 3 of the file into an array:

$file_contents = file( $filename, 'r' );

Now loop through 2 the contents of the array, splitting the 1 strings and examining the email address:

foreach ( $file_contents as $line ) {
    list ( $username, $email ) = str_split( ',' $line );
    if ( trim( $email ) == $string ) {
        // A match was found. Take appropriate action.
    }
}
Score: 1

I think the easiest solution is to use file() with 2 str_getcsv().

The code would be something 1 like this:

foreach (file($fileName, FILE_SKIP_EMPTY_LINES) as $line) {
    $columns = str_getcsv($line); // Where $columns[0] and $columns[1] hold the username and email respectively.
}
Score: 1

I truly believe that all examples in other 5 answers works!
But all they are slow, because 4 all of them travers each line in csv file...
I 3 have another example how to find desired 2 string:

$command = sprintf("grep '%s,%s' -Er %s", $userName, $email, $file);
$result = `$command`;

Yes it some kind of dark matter, but 1 it really works and it really fast!

Score: 0

While fgetcsv is potentially a more elegant 4 solution, that doesn't answer your original 3 question: your second array element has 2 a newline, and you're comparing against 1 a string that doesn't.

To fix:

if ($string == str_replace('"','', chop($thisarray[1]))) {

More Related questions