Home  >  Article  >  Backend Development  >  How to determine whether a string exists in an array in php

How to determine whether a string exists in an array in php

PHPz
PHPzOriginal
2023-04-26 14:19:19507browse

In PHP, querying whether a string exists in an array is a common operation. You can use the in_array() function to determine whether a string exists in an array.

The in_array() function has two parameters. The first parameter is the string to be queried, and the second parameter is an array. The function searches for a string in the array and returns TRUE if found, otherwise it returns FALSE.

The following is a sample code using the in_array() function:

In the above code, $fruits is an array variable that contains several strings. Use the in_array() function to find whether "banana" is in the array. If it is, output "found", otherwise output "not found".

You can also use the array_search() function to find the index position of a string in the array. If found, the function returns the index value of the string, otherwise it returns FALSE. The following is a sample code for the array_search() function:

In the above code, the array_search() function is used to find the position of the "banana" string in the array. If found, output the position of the string, otherwise output "not found".

It should be noted that the in_array() and array_search() functions are case-sensitive. If you need to ignore case, you can use strcasecmp() in conjunction with array_search(), or use the array_map() function to convert case before querying.

The above introduces the method of determining whether a string is in an array in PHP. You can choose the appropriate function to operate according to the actual situation.

The above is the detailed content of How to determine whether a string exists in an 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