Php array using a variable

Why does this not find the word as a variable?
But if i use in_array(‘naughtyword’, $wordArr) as a hard code it works??

	$wordArr = [];	
	$words = "SELECT * FROM aarude;";
	$words = $dbh->prepare($words);
	$words->execute();
	if($words->rowCount() > 0){
		while ($word = $words->fetch (PDO::FETCH_OBJ)){
			$rude = $word->word;
			array_push($wordArr,$rude);
		}
	}

	$search = "SELECT * FROM products ORDER BY date DESC;";
 	
	$search = $dbh->prepare($search);
	$search->execute();
	if($search->rowCount() > 0){
			while ($s = $search->fetch (PDO::FETCH_OBJ)){
				$title = strtolower($s->title);
				$test = '"'.$title.'"';
				if(in_array($title, $wordArr)){ echo "NAUGHTY!!!<br/>"; };
				
				echo $title."<br/><br/>";
				
				echo $s->description."<br/><br/>";;
			}
	}

Because in_array() is looking for an exact match for the whole title, not just any part of the title string.
So if the array is:-

$array = ['foo', 'bar', 'baz'];

and the title is:-

$title = "Foo goes to the bar with Baz";

It won’t find a match. It will match if the title is:-

$title = 'foo';

On a side note, that whole block of code could be optimised a lot, but that’s another subject.

Let’s look at the first block of code, before the second query:-

	$wordArr = [];		// No need to set an array, PDO will fetch directly into a new array
	$words = "SELECT * FROM aarude;";	// Don't use * unless you absolutlely need to fetch every column, here you only need one column
	$words = $dbh->prepare($words); // No need to prepare and execute a hard coded query with no variables
	$words->execute();
	if($words->rowCount() > 0){ // This isn't the best way to check a result
		while ($word = $words->fetch (PDO::FETCH_OBJ)){ // No point fetching as an object if you are not using it as an object
			$rude = $word->word;
			array_push($wordArr,$rude); // Use fetchAll to put straight to an array
		}
	}

We can shorten that to a single line of code which will get the same result more efficiently:-

$wordArr = $dbh->query("SELECT word FROM aarude")->fetchAll(PDO::FETCH_COLUMN);

I’ll leave the second part as it doesn’t work anyway and needs a complete rethink…

Okay thanks,

I’m going to scrap this anyway and perform an autocomplete before this data gets to database in the first place within the user form.

Data submitted to your site can come from anywhere, not just your form, can be set to anything, and cannot be trusted. Any validation you do in the browser is only a nicety for legitimate visitors. You must trim, mainly so that you can detect if a value is all white-space characters, then validate the data on the server before using it.

Who is able to submit product data to your site? Shouldn’t it be a logged in, trusted, manager/administrator?

if(count(array_filter($wordArr,function($word) { return str_contains($title,$word); })) > 0)