检查所有数组值是否存在于另一个数组值中

时间:2018-04-17 13:17:13

标签: php arrays

我有一个我希望与另一个数组匹配的数组,第一个数组中的所有值必须在第二个数组内,所以如果第二个数组长度小于第一个数组长度,它会自动变为false。例如:

$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","milk","book");
$this->matchArray($products,$availableProducts); //return true because  all $products value inside $availableProducts value too

$products = array("soap","milk","book");
$availableProducts = array("milk","tea","book","soap","oil");
$this->matchArray($products,$availableProducts); //return true because  all $products value inside $availableProducts value too

$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","salt","paper");
$this->matchArray($products,$availableProducts); //return false because  only one of $products value inside $availableProducts value

$products = array("soap","milk","book");
$availableProducts = array("milk","book");
$this->matchArray($products,$availableProducts); //return false because  only two of $products value inside $availableProducts value 

2 个答案:

答案 0 :(得分:2)

PHP提供了广泛的array functions

您正在寻找array_diff(),根据文档:

  

将array1与一个或多个其他数组进行比较,并返回array1中任何其他数组中不存在的值。

答案 1 :(得分:1)

您可以使用array_diff()

  

array_diff - 计算数组的差异

     

将array1与一个或多个其他数组进行比较并返回   array1中的值,不存在于任何其他数组中。

<?php

$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","milk","book");

$difference = array_diff($products,$availableProducts);

if(count($difference)==0){

  echo "all products availabale";
}else{

  echo implode(',',$difference) ." are not available";
}

输出: -

  1. https://eval.in/989587

  2. https://eval.in/989588

  3. https://eval.in/989593

  4. https://eval.in/989596