I am trying to make a function in PHP which receives a string (name of a dependency) and depending on the name gives it a "gender" (the/the), as shown below:
$depe =ucwords($_POST['depe']);
function gen_depe($var){
// $var = substr($var, 0, 100);
$facu = 'FACULTAD';
$esc = 'ESCUELA';
$coord = 'COORDINACION';
$centro = 'CENTRO';
$inst= 'INSTITUTO';
if( (strpos($var,$facu) === false) OR (strpos($var,$esc)===false) OR (strpos($var,$coord)===false) ){
return "La $var ";
}elseif( (strpos($var,$centro) === false) OR (strpos($var,$inst)===false) ){
return "el $var";
}else{
echo "Algo está mal";
}
}
echo gen_depe($depe);
the problem arises that it always returns the "the" option regardless of whether CENTER OR INSTITUTION is placed, and I cannot find the solution, I would greatly appreciate your help, thank you.
Your problem is that the strpos function returns a position (
int
) orfalse
the string you are looking for was not found. That is, the comparison withfalse
should only be done to see if the string you're looking for doesn't exist in your variable$var
.For it to work in your code you should add the symbol " ! " before the parentheses.
You are also converting to lowercase the text string you are receiving with the ucwords function .
The value of your variables should also be lowercase:
An alternative to your code is to use two arrays. In one you would have the elements that belong to the feminine gender and in the other to the masculine gender. And to know which gender it corresponds to, you would use the in_array function .
I would use this formula to solve
As an additional note I add an element at position 0 because array_search returns position or false and the if takes 0 and false as false.
Taking into account that the evaluated values would have to be chosen from some list, you could solve the problem as follows:
And if the input string is open text, I suggest reconsidering that feature, since the returned error would be meaningless if the allowed values were not suggested to the user.