How to check a value exists in an array is a general requirement when using array. We can do it by iterating through the array one by one and checking that the searched value exist or not. But now a days, everybody expects a short method means using built in functions in the language. PHP also provides the built in function in_array() for checking the value in an array. in_array — Checks if a value exists in an array (php4, php5) syntax
1 | bool in_array ( mixed $searchedvalue , array $arraytosearch [, bool $strict = FALSE ] ) |
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the searched value in the array. Return boolean value Returns TRUE if searched value is found in the array, FALSE otherwise. Note: in_array() is case-sensitive search. Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | $ab = array('apple','banana','pea','grapes',12); //1. if(in_array('papaya',$ab)) { echo "Got papaya"; } //output : Got papaya //2. if(in_array('Papaya',$ab)) { echo "Got papaya"; }else { echo "Not Got Papaya" } //output : Not Got Papaya if(in_array('12',$ab)) { echo "Got 12"; } // output : Got 12 if(in_array('12',$ab,true)) { echo "Got 12"; }else { echo "Not Got 12" } //output : Not Got 12 // due to type mismatch : third parameter is true for checking value type if(in_array(12,$ab,true)) { echo "Got 12"; } // output : Got 12 |
By reading these examples, you can get proper understanding of using in_array() PHP function. If still have any doubt, you can write to us by commenting on the post, we will revert back to you with possible solution as soon as possible.