使用循环和 if 条件 - PHP 匹配字符串/数组字符串


match string/string of array using loop and if condition - php

这是一个困扰我的常见简单问题。我有一个存储在变量中的数组,我想从存储在变量 ($match) 中的字符串中搜索并匹配字符串数组值 ($myarray)。如何使用循环匹配值并计数(如果有多少匹配项)?我应该使用 for 循环还是 while 循环,还是每个循环?这是我的示例数据。

$myArray = array('one', 'two', 'three', 'four', 'five');
$count = count($myArray);
$match = 'six';
$match2 = array('car', 'dog');
for ($myArray=0; $myArray < $count; $myArray++) { 
    if($myArray == $match){
        echo 'do something';
    }else{
        echo 'do something';
    }
}

还可以将一个数组的值与另一个数组匹配吗?例如,我想搜索 $myArray 的所有值并将其与 $match 2 的值匹配并返回所有匹配项(例如:2 项中的 10 项匹配项)

我在循环或处理数组方面没有足够的知识。谢谢你的帮助。

我认为您正在寻找的功能是array_intersect() .你给这 2 个数组,它返回一个包含它们共同元素的数组。然后,您可以使用count()获取号码。

$matches = count(array_intersect($myArray, $match2));

你需要一个变量,而不是你的数组变量,才能查看周期中的当前索引,我们将这个命名为index,然后将该位置的字符串与你想要匹配的字符串进行比较。

$myArray = array('one', 'two', 'three', 'four', 'five');
$count = count($myArray);
$match = 'six';
$match2 = array('car', 'dog');
$numberMatches = 0;
for ($index=0; $index < $count; $index++) { 
    if($myArray[index] == $match){
        echo "It matches" ;
        $numberMatches++;
    }else{
        echo "It doesn' t match";
    }
}