How to check if an element exists in an array in PHP

Using in_array() PHP function you can verify if an element exists in an array. In this topic, we will see how we can use in_array() function and display message depending on whether an item exists in the array or not. Take a look at the below code:


<?php
$languages = array('React','C++','PHP','Python','Java');
$find = "PHP";
    if (in_array($find,$languages))
      echo $find." exists in the Array
"; else echo $find." does not exist in the Array
";

Here, $languages is an array and we are checking if "PHP" exists in the array. In this case output will be "PHP exists in the Array".

Let us see various cases, we can use in_array() function in different ways and display the output. The array has few string elements and a number (99) element in it. Let me search "Golang" now:


<?php
$languages = array("React","C++","PHP","Python","Java","88",99);
// check if Golang exists in array
    $find = "Golang";
    if (in_array($find,$languages))
      echo $find." exists in the Array
"; else echo $find." does not exist in the Array
";

It gives output as "Golang does not exist in the Array"

Let us search "php" (lower case) now:


<?php
$languages = array("React","C++","PHP","Python","Java","88",99);
// check if php exists in array
    $find = "php";
    if (in_array($find,$languages))
      echo $find." exists in the Array
"; else echo $find." does not exist in the Array
";

Output is "php does not exist in the Array". Since this search is case-sensitive that is why it can not find "php".

You can use a third parameter as TRUE or FALSE. If you give third parameter as TRUE, it will work as strict mode and in_array() will check the value as well as the type. So, searching for "99" and 99 will give different results when used with third parameter as TRUE. See below:


<?php
$languages = array("React","C++","PHP","Python","Java","88",99);
// use strict mode to search for value and type
    $find = 99;
    if (in_array($find,$languages))
      echo $find." exists in the Array
"; else echo $find." does not exist in the Array
"; $find = "99"; if (in_array($find,$languages,true)) echo "\"$find\" exists in the Array (strict mode)
"; else echo "\"$find\" does not exist in the Array (strict mode)
";

If you run above code, in the first case, it will display "99 exists in the Array" and in the second case it will display - '"99" does not exist in the Array (strict mode)'. See in the first case, it is a number and in the second case, it is a string.

find if value exists in an array in phpConclusion

This is an example of using array function in PHP. While coding, specially, during string manipulation, you might have to use various PHP functions on strings and arrays. in_array() is very useful for searching in an array.