Using in_array()
PHP function you can verify if an element exists in an array or not. In this topic I will show how you can use in_array()
function and print message depending on whether an item exists in the array or not. Look below code how it is used:
Here, I have an array $languages
and I am checking if "PHP" exists in the array. In this case output will be "PHP exists in the Array".
Let us see various cases, see how I am using in_array()
function in different cases and displaying the output. The array has few string elements and one number (99) element in it. Let me search "Golang" now:
It gives me output as "Golang does not exist in the Array"
Let me search "php" now:
Output is "php does not exist in the Array". Since this search is case-sensitive that is why it can not find "php".
You can use a third parameter as TRUE or FALSE. If you give third parameter as TRUE, it will work as strict mode and in_array()
will check the value as well as the type. So, searching for "99" and 99 will give different results when used with third parameter as TRUE. See below:
If you run above code, in the first case, it will display "99 exists in the Array" and in the second case it will display - '"99" does not exist in the Array (strict mode)'. See in the first case, it is number and second case it is a string.