Search code examples
phpfilecomparison

Why the if doesn't do the comparison?


I'm trying to compare two numbers through an if statement, but it doesn't work. One number comes from a database in a .txt file.

This is the database where the number comes from:

Number of registrations: 64
50|name|surname|email|12412412
61|name|surname|email|07802634202 

This is the script :

$phone = "07802634202";

// Get th file from the database and convert it in an array
$database = file("database.txt", FILE_SKIP_EMPTY_LINES);
// Get the lenght of the database "Rows"
$database_length = count($database);

// Transform  in an array the string inside each row and save them in a variable 
for($a = 1; $a < $database_length; $a++) {

  $data[$a] = explode("|", $database[$a]);
}

// Check if the last variable 'Number' in a row is equal to $phone 
foreach($data as $key => $val) {

  echo "Database val: " . $val[4];
  echo "Phone val: " . $phone;
  // If it's equal print yep otherwise nope
  if ($val[4] == $phone) { 

    echo "\n yep \n"; 
  } else { 

    echo "\n nope \n";
  }
}

This is what the console prints:

Database val: 12412412                                                                                                                                          
Phone val: 07802634202                                                                                                                                          
 nope                                                                                                                                                           
Database val: 07802634202                                                                                                                                       
Phone val: 07802634202                                                                                                                                          
 nope    

Please if something is not clear, just let me know. I've tried everything without any results.

Thanks for your help :)


Solution

  • As your data is from various sources, it's always worth trimming the fields to ensure any leading or trailing spaces are removed.

    if (trim($val[4]) == trim($phone)) {...}
    

    Just a slight addition, worth adding FILE_IGNORE_NEW_LINES to the call to file() as otherwise you will end with with the new line at the end of the line.