How to check a value exists in an array

How to check a value exists in an array is a general requirement when using array. We can do it by iterating through the array one by one and checking that the searched value exist or not. But now a days, everybody expects a short method means using built in functions in the language. PHP also provides the built in function in_array() for checking the value in an array. in_array — Checks if a value exists in an array (php4, php5) syntax

bool in_array ( mixed $searchedvalue , array $arraytosearch [, bool $strict = FALSE ] )

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the searched value in the array. Return boolean value Returns TRUE if searched value is found in the array, FALSE otherwise. Note: in_array() is case-sensitive search. Examples:

$ab = array('apple','banana','pea','grapes',12);
//1.
if(in_array('papaya',$ab))
  {
  echo "Got papaya";
 }

//output : Got papaya

//2.
if(in_array('Papaya',$ab))
  {
  echo "Got papaya";
 }else
{
 echo "Not Got Papaya"
}

//output : Not Got Papaya

if(in_array('12',$ab))
  {
  echo "Got 12";
 }

// output : Got 12

if(in_array('12',$ab,true))
  {
  echo "Got 12";
 }else
{
 echo "Not Got 12"
}
//output : Not Got 12  // due to type mismatch : third parameter is true for checking value type

if(in_array(12,$ab,true))
  {
  echo "Got 12";
 }

// output : Got 12

By reading these examples, you can get proper understanding of using in_array() PHP function. If still have any doubt, you can write to us by commenting on the post, we will revert back to you with possible solution as soon as possible.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.