在PHP中检查一个数组中的值是否存在于另一个数组中

huangapple go评论72阅读模式
英文:

Checking if a values from array exists in a second array in PHP

问题

我正在尝试检查数组1中的任何值是否存在于数组2中。我目前正在尝试使用foreachin_array的组合来实现此目标:

数组1:

Array
(
	[checkThis1] => 1234567
	[checkThis2] => 7654321
	[checkThis3] => 0101010
)

数组2:

Array
(
	[0] => 0101010
	[1] => 9324812
)

代码:

foreach ($array1 as $checkThis) {
		if (in_array($checkThis, $array2)) {
			echo "checkThis exists in array2";
			return true;
		}
		echo "checkThis does not exist in array2";
		return false;
	}

正如您在上面所看到的,这两个数组的格式相同,因此不应该引起任何问题。但出于我不知道的原因,这个循环总是返回false,即使我确信该值存在于这两个数组中。

英文:

I am trying to check if any of the values from array 1 exist in array 2. I am currently trying to achieve this using a combination of foreach and in_array:

Array 1:

Array
(
	[checkThis1] => 1234567
	[checkThis2] => 7654321
	[checkThis3] => 0101010
)

Array 2:

Array
(
	[0] => 0101010
	[1] => 9324812
)

Code:

foreach ($array1 as $checkThis) {
		if (in_array($checkThis, $array2)) {
			echo "checkThis exists in array2";
			return true;
		}
		echo "checkThis does not exist in array2";
		return false;
	}

As you can see up here the two arrays are formatted the same way so this should cause no issues. For some reason unknown to me this loop always returns false, even though I am sure that the value exists in both of the arrays.

答案1

得分: 1

return 结束代码执行。你的 foreach 仅完成了其第一个迭代。如果 0101010 是第一个数组中的第一个项目,它将返回 true。要获取两个数组中都存在的项目,使用 array_intersect

$arrayOne = [
    'checkThis1' => 1234567,
    'checkThis2' => 7654321,
    'checkThis3' => 0101010
];

$arrayTwo = [0101010, 9324812];

$intersect = array_intersect(array_values($arrayOne), $arrayTwo);

要检查第二个数组中是否存在任何项目,请检查交集的计数是否大于 0。

$hasAny = (count(array_intersect(array_values($arrayOne), $arrayTwo)) > 0); // true or false
英文:

return ends code execution. Your foreach is only completing its first iteration. If 0101010 was the first item in the first array it would return true. To get the items that exist in both arrays use array_intersect.

$arrayOne = [
    'checkThis1' => 1234567,
    'checkThis2' => 7654321,
    'checkThis3' => 0101010
];

$arrayTwo = [0101010, 9324812];

$intersect = array_intersect(array_values($arrayOne), $arrayTwo);

To check if any of the items exist in the second array check if the count of the intersect is bigger than 0.

$hasAny = (count(array_intersect(array_values($arrayOne), $arrayTwo)) > 0); // true or false

huangapple
  • 本文由 发表于 2023年7月18日 03:35:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定