Home >Backend Development >PHP Problem >How to check if value is in array in php

How to check if value is in array in php

PHPz
PHPzOriginal
2023-04-18 16:00:15453browse

PHP is a powerful programming language with many built-in functions that make it easier for developers to write code. One of the built-in functions is a function that checks whether a value is in an array. In PHP, this function is called the in_array() function.

The in_array() function is an important array function in PHP. It is used to check whether a value is in an array. Its syntax is as follows:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

The parameters of the in_array() function are as follows:

  1. needle parameter: the value to be found, which can be any type of variable.
  2. haystack parameter: the array to be searched.
  3. strict parameter: an optional Boolean value, the default is FALSE, indicating that types are not distinguished when comparing values.

The following is a simple example showing how to use the in_array() function to check whether a value is in an array:

$fruits = array("apple", "banana", "orange", "kiwi");
if (in_array("apple", $fruits)) {
    echo "Found";
} else {
    echo "Not found";
}

In this example, we create a file named array of $fruits and checks if it contains an element named "apple". Since the array does contain "apple", the code will print "Found", otherwise it will print "Not found".

Another example showing how to use the in_array() function to check if a value is in an array and remove the value from the array:

$fruits = array("apple", "banana", "orange", "kiwi");
if (in_array("kiwi", $fruits)) {
    echo "Found";
    unset($fruits[array_search("kiwi", $fruits)]);
} else {
    echo "Not found";
}
print_r($fruits);

In this example, we check the array Whether $fruits contains an element named "kiwi". Since the array does contain "kiwi", the code will output "Found" and use the unset() function to remove it from the array. Finally, we use the print_r() function to print the contents of the $fruits array.

Summary:

In PHP, you can easily check if a value is in an array using the in_array() function and take appropriate action. This function helps us write code faster and manage data efficiently.

The above is the detailed content of How to check if value is in array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn