Check if value exists in array PHP
In this post, you will learn how to check if a value exists in an array using the PHP programming language.
Array is used when there is a requirement to add more items in a single variable. PHP provides array() construct to create an array. PHP also provides several in-built useful methods to operate and access the elements of array. Here, we have used both in-built and custom methods to check if value exists in array.
PHP Check if value exists in array using in_array() method
The in_array() function of PHP is used to check whether a value exists in an array or not.
Syntax-in_array(search_value, array, type)
Here, search_value is the value to search in the array, array specifies the array to search, and type is optional. If it is set to true, the function checks the type of the search_value.
Example-
<?php
// Creating array
$fruits = array("Apple", "Orange", "Guava", "Kiwi");
// Checking if Apple exists in an array.
if (in_array("Apple", $fruits)) {
echo "The Apple value exists.";
} else {
echo "The value doesn't exists.";
}
?>
Output of the above code:
The Apple value exists.
PHP Check if value exists in associative array using in_array() method
In the given PHP program, we have used the in_array() method to check if a value exists in an associative array or not.
<?php
// Creating array
$fruits = array(0=>"Apple", 1=>"Orange", 2=>"Guava", 3=>"Kiwi");
// Checking if Guava exists in an array.
if (in_array("Guava", $fruits)) {
echo "The Guava value exists.";
} else {
echo "The value doesn't exists.";
}
?>
Output of the above code:
The Guava value exists.
PHP Check if value exists in array using array_search() method
The array_search() function in PHP searches an array for a given value and returns the key.
Syntax-array_search(value, array, strict)
Here, the value specifies the value to search for, array specifies the array to search for and strict is optional. If this parameter is set to TRUE, then this function will search for identical elements in the array.
<?php
// Creating array
$fruits = array(0=>"Apple", 1=>"Orange", 2=>"Guava", 3=>"Kiwi");
// Checking if Kiwi exists in an array.
if (array_search("Kiwi", $fruits)) {
echo "The Kiwi value exists.";
} else {
echo "Value doesn't exists";
}
?>
Output of the above code:
The Kiwi value exists.
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address