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 a message depending on whether an item exists in an 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 a 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 it can not find "php".

You can use a third parameter as TRUE or FALSE. If you give a third parameter as TRUE, it will work in 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 the 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 the 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 that 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 an array function in PHP. While coding, especially, 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.

Post a Comment

Save my Name and Email id for future comments