📜  数组php中的多个值匹配(1)

📅  最后修改于: 2023-12-03 14:54:58.421000             🧑  作者: Mango

数组PHP中的多个值匹配

在PHP中,匹配数组中的多个值是一项常见的任务。通常,我们需要通过for循环来遍历数组并逐个比较值。这是非常低效的。

PHP提供了几种有效的方法来匹配数组中的多个值。本文将介绍其中两种:in_array()函数和array_intersect()函数。

in_array()函数

in_array()函数是PHP内置的一个函数,用于检查数组中是否包含某个值。它可以接受两个参数:

in_array(needle, haystack);

needle是要查找的值,haystack是要查找的数组。如果needle在haystack中存在,该函数将返回True,否则返回False。

要在数组中匹配多个值,可以使用in_array()函数嵌套。例如:

$fruits = array("apple", "banana", "orange", "mango");
if (in_array("apple", $fruits) && in_array("banana", $fruits)) {
    echo "Both apple and banana are in the fruits array.";
} else {
    echo "Either apple or banana is not in the fruits array.";
}

如果数组中包含apple和banana,则输出“Both apple and banana are in the fruits array.”。否则,输出“Either apple or banana is not in the fruits array.”。

array_intersect()函数

array_intersect()函数是另一个PHP内置函数,它用于查找两个或多个数组之间的交集。它可接受两个或多个数组作为参数。

例如,假设我们有两个数组:

$fruits1 = array("apple", "banana", "orange", "mango");
$fruits2 = array("banana", "watermelon", "pear");

要查找这两个数组之间的交集,我们可以使用array_intersect()函数:

$common = array_intersect($fruits1, $fruits2);
print_r($common);

这将得到以下输出:

Array
(
    [1] => banana
)

交集是一个新数组,其中包含两个数组之间共同存在的值。在这个例子中,$fruits1和$fruits2数组共同包含一个值“banana”。

要匹配多个值,只需将这些值组合成一个数组,然后将它作为array_intersect()函数的参数即可:

$common = array_intersect($fruits1, array("apple", "banana"));
if (!empty($common)) {
    echo "Both apple and banana are in the fruits1 array.";
} else {
    echo "Either apple or banana is not in the fruits1 array.";
}

这将得到以下输出:

Both apple and banana are in the fruits1 array.

由于$fruits1数组中包含apple和banana,因此得到了输出“Both apple and banana are in the fruits1 array.”。

以上是PHP中匹配数组中多个值的两种有效方法。它们都比使用for循环更高效,并且易于实现。