问题
hello i would like to create a function that checks if an etry contains some words.
for my login-script i would like to create a function that checks if the $_POST has some keywords in it.
therfor i have thought to create an array that contains the words i'm looking for like that:
function value_check($a, $b){
$haystack = array ($a, $b)
$words = array ("abc", "def");
if(strpos($haystack, $words) === true) {
return ($a or $b, or both where strpos === true);
}
return false;
}
and i would like to call that function by:
$valid_value = value_check($a, $b);
if ($valid_value['a'] === true) {
//do something
}
if ($valid_value['b'] === true) {
//do something
}
thanks alot.
Okay, to clarify my question i would like to shorten my code. instead of using:
...else if ($a === "abc" || $a === "Abc" ) {
$errors['a'][] = "text";
}else if ($b === "def" || $a === "Def" ) {
$errors['b'][] = "text";
}
i thought i can do it a little bit more comfortable while using a function that checks easily if there is a that specific string in that array. hope it will be clear now. thanks.
回答1:
Read this in_array for search in array. And this explode for creating an array from a string like Ascherer suggested.
function value_check ($haystack) {
foreach ($words as $element) {
if (in_array($element,$haystack) {
$result[] = $element;
}
}
return $result;
}
a call
$somestuff = array($a,$b);
$valid_value = value_check ($somestuff);
foreach ($valid_value as $value) {
// do something
}
来源:https://stackoverflow.com/questions/15030802/function-to-check-array-strpos-and-return-an-array