How to check if a value exists in an array in PHP?
Answer: Using in_array()
function
We can check if a value exists in an array by using the in_array() function of PHP. This function is used to check whether the value exists within the array or not. It returns true if the value we are looking for exists within the array. otherwise, it returns false.
Example: Using in_array()
function
In the given example, we checked whether the value CSS exists within the array $proglang or not using the in_array()
function along with the if statement. If the value exists then the output will be Value exists within the array and if not then the output will be Value does not exist in array".
<!DOCTYPE html>
<html>
<head>
<title>If a value exists in an array</title>
</head>
<body>
<?php
$proglang = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
if(in_array("CSS", $proglang)){
echo "Value exists in array";
}else{
echo "Value does not exists in array";
}
?>
</body>
</html>
This value exists in array
Using array_search()
function
The array_search()
function searches an array for value and returns its key. The function return key of the value if it is present within the array otherwise, it returns false.
If the same value is present more than once, then this function returns the key of the first occurred value.
Example: Using array_search()
function
In the given example, we have searched for the value Developer within the array $employee using the array_search()
function, and in return, we get its key John. After that, we have checked whether the value exists within the array or not using the if statement. If the value is present within the array, then the output will "Value exists," and if not, then the output will be "Value doesn't exist."
<!DOCTYPE html>
<html>
<head>
<title>If a value exists in an array</title>
</head>
<body>
<?php
$employee = array("Harry" => "HR", "John" => "Developer", "Jack" => "Management");
echo array_search("Developer", $employee);
echo "<br>";
if (array_search("Developer", $employee)) {
echo "Value exists";
} else {
echo "Value doesn't exist";
}
?>
</body>
</html>
John
Value exists
Conclusion
In this lesson, we have learned how to check if a value exists within the array or not. Here, we have discussed two predefined functions by which we have check whether the value exists within the array or not; these functions are:
- in_array() function
- array_search() function