How to check if value is in array in php

PHPz
Release: 2023-04-18 16:02:35
Original
446 people have browsed it

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";
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template