Check if a value exists in an array in PHP

Here we are going to see an example where we will check if a specific value exists in an array or not in PHP programming language. This task is going to be quite easy.

So let’s continue…

First of all, let’s take a PHP array for example:

$num_arr = array(526, 127, 98, 236, 721);

Now in our above array we are going to check if a specific number or value exists in our array or not with PHP program.

Before I go through let’s introduced to an in-built PHP function in_array(). This function is going to be so helpful for our task.

The in_array() PHP function uses to determine if a specific value exists in an array or not. So we can use this function to check if our value exists in the array.

Now, remember about our array which contains some numbers. We are going to check if our array contains the number 236 or not.

Below is our complete PHP code to check if 236 in the array:

<?php 
$num_arr = array(526, 127, 98, 236, 721); 


if (in_array("236", $num_arr)) 
{ 
echo "Number exists"; 
} 
else
{ 
echo "Number not exists"; 
} 
?>

The above code will give the output that is given below:

Number exists

We can see that it is giving the output “Number exists” because the number 236 is in our array. If we check for any other number that does not exist in our array, then it will show another output.

Also, read:

 

We can also check for the string. Below is another example where we are checking if a string exists in an array or not:

<?php
$clr_arr= array("red", "green", "yellow", "blue"); 


if (in_array("green", $clr_arr))
{
echo "Color available";
}
else
{
echo "Color not available";
}
?>

In our above code, we have an array which contains the name of four colors. From the above code, you can understand that we are checking for green color. As the color green exists in our array, so it will give us the output that is given below:

Color available

I hope, you have understood how we can check if a value exists in an array in PHP. You have also got some idea about the in_array() PHP function and its usage from this article.

 

Leave a Reply

Your email address will not be published. Required fields are marked *