Reputation: 19
I have a mysql_query
to select *
from an 'english'
list database and mysql_fetch_assoc
returns an array. I try to search word 'flick'
(which actually exists in the database) by using in_array()
if 'flick'
is found, it shouldn't be shown but it is shown. I think in_array
function does not find the word 'flick'
. Please look at code below:
<?php
error_reporting(E_ALL);
require 'db.php';
function spellcheck($word)
{
$output = array();
$word = mysql_real_escape_string($word);
$words = mysql_query("SELECT `word` FROM `english` WHERE LEFT(`word`, 1) = '" .
substr($word, 0, 1) . "'");
while(($words_row = mysql_fetch_assoc($words)) && (in_array($word, $words_row)==false))
{
similar_text($word, $words_row['word'], $percent);
if($percent > 82)
{
$output[] = $words_row['word'];
}
}
return (empty($output)) ? false : $output;
}
if (isset($_GET['word']) && trim($_GET['word']) != null)
{
$word = $_GET['word'];
$spellcheck = spellcheck($word);
if ($spellcheck !== false)
{
echo '<pre>' . print_r($spellcheck, true) . '</pre>';
} else {
echo '<p>' . $word . ' spelled correctly, or no suggestions founds.</p>';
}
}
?>
<form action="" method="GET">
Check single word spelling:
<input type="text" name="word" />
<input type="submit" value="Check" />
</form>
The code returns:
Array (
[0] => flick
[1] => flicks
)
But it should be:
"spelled correctly, or no suggestions founds."
Upvotes: 0
Views: 363
Reputation: 19
After 2 days working on my problem I found the answer.
the mistake is in the output of the query by mysql_fetch_assoc
. Actually it returns an associative array but every key is added a space (' ') after that.
So, the result is not like abcdefg
. The result is like a b c d e f g
. It means when I search a special word in the associative array, the in_array()
function returns false. Because for example the word 'flick'
is not equal to 'flick '
and there is a space after the keys in array. I used trim()
function and solved my problem:
while ($rows = mysql_fetch_assoc($query))
{
foreach($rows as $key)
{
$key = trim($key);
$array[] = $key;
}
}
if (in_array($word, $array))
{
echo "The word is spelled correctly";
} else {
foreach($array as $key)
{
similar_text($word, $key, $percent);
if ($percent > 82)
{
$output[] = $key;
}
}
}
tank you for your paying attention to my answer.
Upvotes: 1
Reputation: 1804
replace this line
while(($words_row = mysql_fetch_assoc($words)) && (in_array($word, $words_row)==false))
with
while(($words_row = mysql_fetch_assoc($words))) {
if((in_array($word, $words_row)==false)) {
and at bottom close if statement
Upvotes: 2