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.
$file_handle = fopen("sources.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] = 'paul') {
echo 'Found';
}
}
fclose($file_handle);
I am trying to check in sources.csv files, for the name 'Paul' .
I can't use a database like MySQL for technical reasons.
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 =)