I’m writing a blacklist word checker. I’ve named the script as blacklist_check.php and it looks like this:
<?php
$black_list = [
'ass',
'anus',
/* many others that i skipped here */
];
function is_black_listed ($word) {
return in_array($word, $black_list);
}
?>
However when I use the is_black_listed function, I always get Warning: in_array() expects parameter 2 to be array, null given.
Should I put the $black_list array inside of is_black_listed function? I don’t want to do it, as the array would always get created when I call the function, instead of it being just one time when I require (or include) the script!
Should I use global $black_list inside of is_black_listed function?
Help me out with the best practice to solve this problem!
Don’t use a global variable, they’re pretty hard to maintain and make your code less readable. Instead, just pass the array to the function:
Then call it with:
Better yet, create a class to do this, and create the array as a member variable: