Reputation: 514
I'm having a .csv with about a hundred lines, each line looking like this:
lastname, firstname, role, ...
I'm searching through the .csv
with the script provided below which works fine.
The only problem is that it returns only matches from the second character of the lastname on. So if I type some firstname -> match, role -> match, astname -> match, lastname -> no match
. Obviously the first character of each line is ignored, but I don't know why. Also PHP does not show ä, ö, ü characters but finds them in the .csv
.
<?php
//returns an array containing each line as value of another array
$csv = array_map('str_getcsv', file('data.csv'));
//get the search parameter from URL
$q=$_GET["q"];
if(strlen($q) > 0) {
$hint="";
foreach($csv as $line){
//if the line contains the search string, append it to the resulting string
if(strpos($line[0], $q, 0) != FALSE) {
$hint = $hint."<p>".$line[0]."</p>";
}
}
}
// Set output to "no suggestion" if no hint was found
// or to the correct values
if ($hint == "") {
$response = "no suggestions";
} else {
$response = $hint;
}
//output the response
echo $response;
?>
Upvotes: 0
Views: 72
Reputation: 12089
Solution to: PHP Loose Comparison and strpos
Zero Index Problem
Limit your conditional statement to an exact type comparison, using !==
:
if(strpos($line[0], $q, 0) !== FALSE) {
$hint = $hint."<p>".$line[0]."</p>";
}
PHP strpos
uses a zero-based string index, so it's actually matching lastname at position 0
and returns that value, which is loosely interpreted as FALSE
. However, using a strict type comparison, such as ===
and !==
limits your conditional statement to look for a match of type (boolean in this case) and value.
In the olden days of programming (when typewriters were used) I resorted to this hack: strpos("_".$string, $match)
.
Upvotes: 2