Checking an element
Check if an element is included in the array: in_array()
The in_array()
function returns a boolean , true
if the element value is in the array (not as the key), or false
if the element is not present.
Strict comparison
By default the behavior is to perform a โlooseโ comparison.
It means true and 1 are considered as โequalsโ.
Why? PHP
is the same when you perform a loose comparisons with ==
, for example: (true == 1)
(is true
). If you want a strict comparison you need to use ===
, for example (true === 1)
(is false
). For the in_array()
function, you have the third (optional) parameter $strict
to define that you want a strict comparison performed. Loose comparison is the default behavior.
First | Second | Strict comparison | Loose comparison |
---|---|---|---|
1 | โ1โ | false | true |
null | array() | false | true |
true | 1 | false | true |
true | โSomethingโ | false | true |
For example
Case Sensitive
The in_array()
function is case sensitive which means "My Test"
and "my tesT"
are different due to the case of the first character of each string and the last character.
One way to obtain a case insensitive comparison is to use strtolower()
โfor each element of the arrayโ.
This can be handled by the array_map()
function. The array_map()
function, applies a function to each element of the array. In this case the function is strtolower()