Part of my application requires validating user input. Some of that input must be inclusive in a list of available choices. For example let's take team names:
$array_one = ["Vikings","Eagles","Jaguars","Patriots"];
$array_two = [
"Vikings"=>1,
"Eagles"=>1,
"Jaguars"=>1,
"Patriots"=>1
]
//Validate using array 1
if(in_array($user_input,$array_one)) {
echo "Valid Input";
}
//Validate using array2
if(array_key_exists($user_input,$array_two)) {
echo "Valid Input";
}
With scenario A the arrays "look" cleaner and less hacky. in_array however has to do an O(n) array search. I believe array_key_exists() or isset($array[$key]) results in an O(1) lookup. The second way feels hacky because I'm actually using keys as values. Is the preferred method to structure my data sets\arrays like the second example to avoid using in_array() or in practice this doesn't matter?