In this HowTo i’ll explain what the php in_array function is and how you might use it.
The PHP in_array function is built in to the PHP language to let you know if a certain value is stored in an array. The function takes two parameters; the value you want to search for and the array in which to search. It then returns 1 if the value was found and nothing if it is not. For example:
It’s handy that the in_array function returns these values depending on the outcome of it’s search. Because the 1 and nothing values are equivalent to true and false the in_array function can just be plugged straight in to an if statement like so:
Of course, you don’t need to put a hardcoded value in to the PHP in_array function. You can also use a variable:
This is really useful if you are using an if statement as above and what to reference the value that was being searched for. For example, “Found PHP in Array” in the above code snippet.
One example of using the in_array function could be when you are checking data that has been returned from a database. If this is converted to an array, you may want to check if the array has the data you were expecting. In a similar way, perhaps you want to check the form data that has been submitted by a user on your site.
The PHP in_array function is a really simple built in PHP tool for checking whether a certain value is present in an array. Because of the values it returns, it can be simply plugged in to an if statement or ternary operator to make quick decisions based on whether a value is in an array or not.