Home  >  Article  >  Backend Development  >  PHP determines whether characters are contained in an array

PHP determines whether characters are contained in an array

WBOY
WBOYOriginal
2023-05-22 22:18:37580browse

In PHP development, we often need to process and judge strings. When determining whether a string contains a certain character, we can use the in_array() function in PHP.

in_array() function is used to determine whether a value exists in an array. The syntax of this function is as follows:

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

Parameter description:

  • value: the value to be judged
  • array: the array to be searched
  • strict : Optional parameter, whether to use strict mode. If strict is TRUE, the types are also checked for equality. Default is FALSE.

Next we will show how to use the in_array() function to determine whether a string is contained in an array.

Suppose we have an array $fruits:

$fruits = array("apple", "banana", "orange", "mango", "kiwi");

Now, we want to determine whether it contains the string "banana", you can use the following code:

if (in_array("banana", $fruits)) {
    echo "数组中包含 'banana'。";
} else {
    echo "数组中不包含 'banana'。";
}

If the fruits are in the array , the script will output: The array contains 'banana'.

If the fruit is not in the array, the script will output: The array does not contain 'banana'.

In addition to determining whether the string is contained in the array, we can also use the in_array() function to determine whether numbers, Boolean types, arrays, etc. exist in the array. Here is some sample code:

// 判断数字是否在数组中
$numbers = array(1, 2, 3, 4, 5);
if (in_array(3, $numbers)) {
    echo "数字 3 在数组中。";
} else {
    echo "数字 3 不在数组中。";
}

// 判断布尔型是否在数组中
$bools = array(true, false);
if (in_array(false, $bools)) {
    echo "布尔型 false 在数组中。";
} else {
    echo "布尔型 false 不在数组中。";
}

// 判断数组是否在数组中
$arrays = array(
    array("apple", "banana"),
    array("orange", "mango")
);
$search_array = array("orange", "mango");
if (in_array($search_array, $arrays)) {
    echo "数组 ['orange', 'mango'] 在主数组中。";
} else {
    echo "数组 ['orange', 'mango'] 不在主数组中。";
}

To summarize, using the in_array() function in PHP can quickly and easily determine whether strings, numbers, booleans, and arrays exist in arrays. When judging strings, be sure to pay attention to capitalization to avoid misjudgment.

The above is the detailed content of PHP determines whether characters are contained in an array. 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