Introduction
PHP in_array function is an inbuilt function in PHP. As the name suggests in_array()
function means, this function checks user-defined element is available in the array or not.
So, basically, if we define the in_array function in technical language, then we can say “The PHP in_array function checks whether the given value exists in an array or not.“
Syntax:
Syntax work: $needle search into the $haystack array if strict mode is set to true.
1 2 |
in_array(mixed $needle, array $haystack, bool $strict = false) |
Parameters
needle
The needle is a searched value or a user-defined value.
Note: If the searched value is a string then the comparison is done in case sensitive manner.
haystack
The haystack is an original array where we perform our search operation with a user-defined value.
strict
If the strict value is true $strict = true
then the in_array function also checks the type of a given element.
PHP in_array Function Return Value
After searching a user-defined value in the array, if the value is found then the in-array function returns true otherwise false.
Example of PHP in_array Function
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $os = array("Mac", "Windows", "Linux"); //this gives o/p if (in_array("Linux", $os)) { echo "Got Linux"; } //this does not gives any output if (in_array("mac", $os)) { echo "Got mac"; } ?> |
The first if block gives output, but the second is not because in array function is case-sensitive.
Output: Got Linux
PHP in_array() With Strict Example
1 2 3 4 5 6 7 8 9 10 11 |
<?php $a = array('10', 12, 13); if (in_array('12', $a, true)) { echo "'12' found with the strict check\n"; } if (in_array(13, $a, true)) { echo "13 found with the strict check\n"; } ?> |
The above example output is 13 found with the strict check and first if the block does not give any output because of strict where the function also checks the type of an element.
in_array() Function with Multidimensional
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $colors = [ ['red', 'green', 'blue'], ['cyan', 'magenta', 'yellow', 'black'], ['hue', 'saturation', 'lightness'] ]; if (in_array(['red', 'green', 'blue'], $colors)) { echo 'RGB colors found'; } else { echo 'RGB colors are not found'; } |
Output:
RGB colors found
Code Highlights:
- Here we first define an array inside the array.
- Then we use a specific array to compare with the whole array using in_array function.
To know more, you can check here PHP: in_array – Manual.
You check all the examples by running them on our code editor Run PHP Code (codingtasks.net).
I hope all things are understandable, please let me know if you are facing any issues at the time of implementation.
Happy Coding..!