PHP: Check If A Value Exists In An Array

Let’s say, you have a value like e.g. a name and you’ll find out, whether this value exists in an array of names or not. How could you do this? Well, it’s quite simple. Here I’ll show you how.


Advertisement

First we need an PHP-Array which contains all our values. In this example I use names.

<?php
// the array
$arrNames = array("Kay", "Joe","Susan", "Frank");
?>

Now I want to determine, whether this array contains an element with the value Susan. So I need a variable, which holds the value:

<?php
// the value
$val = 'Susan';
?>

Now let’s check the array for the name. To do this I use the PHP-Function in_array(). This function needs at least two arguments. The first argument is the value, we search for. The second argument ist the array, where we search for the value. There is a third optional argument, which can be used with an boolean value. This third argument is flase by default. If set to true, the function will also check the types.

<?php
// check $arrNames for $val
$boolResult = in_array($val,$arrNames);
// $boolResult will now be true or false (in our example it's true
?>

That’s it! 😉


Advertisement
(Visited 790 times, 1 visits today)

Leave a Comment