How to Check If a Value Exists in an Array Using PHP?

Problem:

You have an array (one-dimensional) which contains lots of values. You want to check if a value exists in that array.

Solution:

You can use in_array() function for the purpose. See the following example-


<?php
$months = array("January", "February", "March", "May", "June", "July", "August", "September", "October", "November", "December");
if(in_array("April", $months))
    echo "April is in the array.";
else
    echo "April is not in the array.";
?>

[wpdm_file id=44]

Output:
April is not in the array.

How it works:
in_array() function is a very simple function. It takes a value as its first parameter and checks if it exists in the second parameter which is an array. As in the above example April is not in the array, so it shows the output.