From the course: PHP for Web Designers

Finding if a value exists in an array - PHP Tutorial

From the course: PHP for Web Designers

Start my 1-month free trial

Finding if a value exists in an array

Sometimes it's useful to find if a particular value exists in an array. One way to do so, is to use a loop to check the value of each array element. But that's inefficient. A much quicker and simpler way, is to use a function called, in array. To see how it works, let's use the indexed array, flowers, which is at the top of this page on lines two and three. The in array function takes two arguments. The value you're looking for and the array you want to examine. Well the array we want to examine is called flowers, and let's choose daffodils. We need to choose a value that we know is going to be there as a good test of whether it works or not. So, let's go down into the HTML. And under the h1 element, let's create a php block. And the first thing we need to do inside there is to create a variable to stall the value we're looking for. The variable I'm going to use, I'm going to call it, order equals daffodils. And then we need an if-else structure to test whether daffodils is in that array. So if and then the condition, and the condition will be in_array and then the two variables, the two arguments that we need to pass to it. The first one is what we're looking for, so that's order, and the second argument is the array we want to inspect, and that's flowers. Closing parenthesis there for in_array. We need a second closing parenthesis for the condition, and then we need a pair of curly braces for the conditional block. And inside there, if it exists we want to display, so we can use echo and would use a double quoted string, have a paragraph and, Yes order are in stock. And then if it fails, we need an else, clause. So else and then that, block down there. And inside there, we'll do echo. And then a little paragraph. Sorry, no order available. So, if we save that page we can now test it in a browser and that will tell us whether daffodils is actually in the flowers array. So we need to go to the zero, nine folder. An the name of the page, is in_array.php. And yes, daffodils are in stock. So let's see what happens if, you choose something that's not there. If we change daffodils to a flower that we know is not in that array. Definitely marigolds are not there. So save that and then go back to the browser, refresh it, Sorry no marigolds available. So, that's how you find out whether a particular value exists in an array. You use the in array function and it takes two arguments. The first argument is the value that you're looking for and the second one is the array that you're looking in. And a useful way to remember the correct order of the arguments is, you're looking for a needle in the haystack and if the needle is in the haystack in array returns true if it's not there, it returns false.

Contents