$arr = array(
'test' => array(
'soap' => true,
),
);
$input = 'hey';
if (in_array($input, $arr['test'])) {
echo $input . ' is apparently in the array?';
}
Result: hey is apparently in the array?
It doesn't make any sense to me, please explain why. And how do I fix this?
That's because true == 'hey'
due to type juggling. What you're looking for is:
if (in_array($input, $arr['test'], true)) {
It forces an equality test based on ===
instead of ==
.
in_array('hey', array('soap' => true)); // true
in_array('hey', array('soap' => true), true); // false
To understand type juggling better you can play with this:
var_dump(true == 'hey'); // true (because 'hey' evaluates to true)
var_dump(true === 'hey'); // false (because strings and booleans are different type)
Update
If you want to know if an array key is set (rather than if a value is present), you should use isset()
like this:
if (isset($arr['test'][$input])) {
// array key $input is present in $arr['test']
// i.e. $arr['test']['hey'] is present
}
Update 2
There's also array_key_exists()
that can test for array key presence; however, it should only be used if there's a possibility that the corresponding array value can be null
.
if (array_key_exists($input, $arr['test'])) {
}
You're using the array as a dictionary but the in_array
function is to be used when you're using it like an array. Check the documentation.
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