在我的例子中如何比较两个数组

时间:2014-07-30 20:06:17

标签: php arrays

我正在尝试比较数组和值

我有类似

的东西
$values = array(1,5,9);
$array = array(1,3,5,7,9);

如果1,5,9在$array

之内,我想得到

所以我做了

foreach($values as $value) {
    if(in_array($value, $array)){
       echo "found";
    }else{
       //i also need get 3 and 7 from `$array` because they are not in values array
       //How do I do this?
    }
}

但是,我还需要从$array获取3和7,因为它们不在值数组中。反正有没有这样做?感谢。

3 个答案:

答案 0 :(得分:0)

你不能在那个foreach中做到这一点,但是,你有没有考虑过这样的事情:

$values = array(1,5,9);
$array = array(1,3,5,7,9);

foreach($values as $value) {
    if(in_array($value, $array)){
       echo "found";
    }
}

//check numbers that are not in array
$diff = array_diff($array, $values);
print_r($diff);

答案 1 :(得分:0)

也许在目标数组中搜索

foreach($array as $value) {
    if(in_array($value, $values)){
       echo "found: ".$value;
    }else{
       echo "not found: ".$value;
    }
}

答案 2 :(得分:0)

只需将它们存储在新数组中:

$valuesNotInArray = array();

foreach($values as $value) {
if(in_array($value, $array)){
   echo "found";
}else{
   //i also need get 3 and 7 from `$array` because they are not in values array
   //How do I do this?
   array_push($valuesNotInArray, $value);
}

然后使用$ valuesNotInArray中的元素做任何你想做的事。

或者说出来:

foreach($values as $value) {
if(in_array($value, $array)){
   echo "found";
}else{
   //i also need get 3 and 7 from `$array` because they are not in values array
   //How do I do this?
   echo $value;
}