Find if a value exist in a CSV file with PHP

后端 未结 3 1734
时光说笑
时光说笑 2021-01-13 15:32

This is my code to check if a row of my .csv file contains a specific name, but it does not work.

I think it has something to do with the if statement.<

相关标签:
3条回答
  • 2021-01-13 16:14

    Since you haven't provided a sample of your file, am submitting the following as an alternative.

    Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.

    if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')

    Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.

    Paul, Larry, Robert
    

    Code:

    <?php
    $search      = "Paul";
    $lines       = file('sources.csv');
    $line_number = false;
    
    while (list($key, $line) = each($lines) and !$line_number) {
    
       $line_number = (strpos($line, $search) !== FALSE);
    
    }
    
    if($line_number){
    
       echo "Results found for " .$search;
    
    }
    
    else{
       echo "No results found for $search";
    }
    

    Footnotes:

    For a case-insensitive search, use stripos()

    $line_number = (stripos($line, $search) !== FALSE);
    

    Row number found on...

    To give you the row's number where it was found:

    $line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
    

    or (case-insensitive)

    $line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
    

    then just echo $line_number;

    0 讨论(0)
  • 2021-01-13 16:16

    Your problem is this line:

    if ($line_of_text[0] = 'paul') {
    

    This will always be true because you are assigning the value paul to $line_of_text[0] with the assign operator =. What you want to do is check if the two are equal, so you need to use the equality operator, ==. The line of code should be:

    if ($line_of_text[0] == 'paul') {
    

    There is also the === equality operator in PHP which checks for the same value AND same type. (This is a particularly nasty feature of PHP when compared to compiled languages)

    e.g. consider: `$foo = 5; $bar = "5";

    if ($foo === $bar)  // this will be false because foo is an int, and bar is a string
    
    if ($foo == $bar) // this will be true
    

    Don't be confused with the != comparison operator:

    if ($foo != $bar) // foo is not equal to bar (note the single =)
    
    0 讨论(0)
  • 2021-01-13 16:18

    Try using in_array instead of ==

    if(in_array('paul', $line_of_text)) {
      // FOUND
    }
    
    0 讨论(0)
提交回复
热议问题