[英]Comparing Array Values in For Loop (PHP)
I have a for loop and I want to compare each value to the other values in the array. 我有一个for循环,我想将每个值与数组中的其他值进行比较。 If there are duplicates, the page redirects.
如果重复,则页面重定向。 How can I compare the value
$name[$x]
to the other values in the $name array whether or not they come before or after $name[$x]
? 如何将值
$name[$x]
与$ name数组中的其他值进行比较,无论它们位于$name[$x]
之前还是之后?
for($x=0; $x<4; $x++) {
if($name[$x] == /*Other members of $name*/) {
header("location:../error/duplicates.php");
exit;
}
}
Why are you doing it like this: 你为什么这样做:
for($x=0; $x<4; $x++) {
if($name[$x] == /*Other members of array*/) {
header("location:../error/duplicates.php");
exit;
}
}
When you could be use array_unique
instead: 当您可以使用
array_unique
代替时:
if (count(array_unique($name)) < count($name)) {
header("location:../error/duplicates.php");
exit;
}
The logic is basically, the array_unique
tells you how many unique items are in an array, right? 逻辑基本上是,
array_unique
告诉您数组中有多少个唯一项,对吗? And if the $name
array contains 4 items, count(array_unique())
should return 4. Which then should match the count()
of the items in $name
, right? 并且,如果
$name
数组包含4个项目,则count(array_unique())
应该返回4。然后,哪个应该与$name
中的项目的count()
相匹配,对吗? Well, if count(array_unique())
has less items than count()
it means duplicates were filtered out. 好吧,如果
count(array_unique())
项目少于count()
则意味着重复项被过滤掉了。
Here it is without the header
but an echo
instead as well as an else
for simpler debugging. 在这里,它没有
header
而是echo
,还有一个用于更简单调试的else
。
$name = array('bob','betty','dan','don'); // no dupes
$name = array('bob','betty','dan','dan'); // dupes
if (count(array_unique($name)) < count($name)) {
echo 'Dupes!';
exit;
}
else {
echo 'No Dupes!';
}
Also you could use array_diff_key
with array_unique
. 您也可以将
array_diff_key
与array_unique
一起array_unique
。 Basically do an array_unique
on $name
and then run that through array_diff_key
comparing it to the original $name
. 基本上在
$name
上执行array_unique
,然后通过array_diff_key
与原始$name
进行比较来运行它。 if the count
is greater than 0
then there is a dupe. 如果
count
大于0
则说明存在重复。
$name = array('bob','betty','dan','don'); // no dupes
$name = array('bob','betty','dan','dan'); // dupes
$name_diff = array_diff_key($name, array_unique($name));
if (count($name_diff) > 0) {
echo 'Dupes!';
echo '<pre>';
print_r($name_diff);
echo '</pre>';
exit;
}
else {
echo 'No Dupes!';
}
EDIT I just edited the last suggestion to use a variable for $name_diff
since if it does return a value more than 0
you now have that value in an array & can act on it. 编辑我刚刚编辑了最后一个建议,为
$name_diff
使用变量,因为如果它返回的值大于0
您现在在数组中具有该值并且可以对其执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.