I'd like a function that checks whether an array's items contain a string. As such:
array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');
And then checking for admin12
should return true as a part of admin12
(admin
) is also a part of the array.
I came this far:
$forbiddennames= array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');
if(in_array( strtolower($stringtocheck), array_map('strtolower', $forbiddennames))){
echo '"This is a forbidden username."';
} else {
echo 'true';
}
}
Only this only echos "This is a forbidden username." when I check for admin
. I want it also to echo when checking for admin12
.
Is this possible (and how)?
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
We know that HashSet doesn't allow duplicate values in it. We can make use of this property to check for duplicates in an array. The idea is to insert all array elements into a HashSet . Now the array contains a duplicate if the array's length is not equal to the set's size.
To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.
Loop through the $forbiddennames
array and use stripos
to check if the given input string matches any of the items in the array:
function is_forbidden($forbiddennames, $stringtocheck)
{
foreach ($forbiddennames as $name) {
if (stripos($stringtocheck, $name) !== FALSE) {
return true;
}
}
}
And use it like below:
if(is_forbidden($forbiddennames, $stringtocheck)) {
echo "This is a forbidden username.";
} else {
echo "True";
}
Demo!
foreach ($forbiddennames as $forbiddenname) {
$nametocheck = strtolower($stringtocheck);
if(strpos($stringtocheck, $forbiddenname) !== false) {
echo "This is a forbidden username.";
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With