Reputation: 5247
I am using a PDO approach to get an array out of database:
$statement = $db->prepare("SELECT sname FROM list WHERE ongoing = 1;");
$statement->execute();
$snames = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($snames);
The dump output is (total 2500 results):
[69]=> string(13) "ah-my-goddess"
[70]=> string(17) "ahiru-no-oujisama"
[71]=> string(13) "ahiru-no-sora"
Then I check if array $snames
contains the new element $sname
:
$sname = current(explode(".", $href_word_array[count($href_word_array)-1]));
if (in_array($sname, $snames) == False)
{
echo "New '$sname'!<br>";
}
else
{
echo "$sname is already in the list. Excluding.<br>";
unset($snames[$sname]);
}
And the output is:
'ah-my-goddess' is already in the list. Excluding.
New 'ahiru-no-oujisama'!
'ahiru-no-sora' is already in the list. Excluding.
Why does it says that 'ahiru-no-oujisama' is the new name? We can see from the DUMP function that the array contains this element.
I have compared the results a thousand times. Notepad finds both names. There are no spaces. Name in the database is the same as in variable..
For the record - I have around 2500 entities in $snames
array and for 95% of records (+-) I am getting the "already exists" result. However, for some I am getting "new".
Is that perhaps some kind of encoding issue? For the table I have DEFAULT CHARSET=latin1. Could that be a problem?
It was suggested that I added a trim operation:
$snames = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
for ($i=0; $i < Count($snames); $i+=1)
{
$snames[$i] = trim($snames[$i]);
}
and:
if (in_array(trim($sname), $snames) == False)
However I get the same problem.
Upvotes: 1
Views: 110
Reputation: 5247
Apparently, the problem was with line:
unset($snames[$sname]);
for some entries I had names such as "70" and "111"
as the result command:
unset($snames[$sname]);
removed elements at that position. Not the elements with such keys!! I.e. That's how program understood it:
unset($snames[77]);
and that's what I was expecting:
unset($snames['77']);
so the line had to be changed to following:
if(($key = array_search($sname, $snames)) !== false)
{
unset($snames[$key]);
}
Upvotes: 1