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.

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

// 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:

// 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.

// 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! 😉

(Visited 2,286 times, 1 visits today)

1 thought on “PHP: Check If A Value Exists In An Array”

  1. Hello, you do very well, this article is really useful for me. What does it mean PHP everywhere and in this today’s world php essential parts of our lives? Why we are using PHP instead of javascript? What is the basic feature that php facilitate us? Is in PHP is there is any fix configuration or configuration that varies in a different situation?


Leave a Comment