Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all array value exist in another array value [duplicate]

Tags:

arrays

php

i have an array that i want to match with another array, all the value inside the first array must be inside the second array, so if second array length is less than the first array length it automatically become false. for example:

$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 
like image 970
mileven Avatar asked Jul 29 '26 22:07

mileven


2 Answers

You can use array_diff()

array_diff — Computes the difference of arrays

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

<?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";
}

Output:-

  1. https://eval.in/989587

  2. https://eval.in/989588

  3. https://eval.in/989593

  4. https://eval.in/989596

like image 181
Anant Kumar Singh Avatar answered Aug 01 '26 12:08

Anant Kumar Singh


PHP provides a wide range of array functions.

You are looking for array_diff(), which according to docs:

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

like image 35
dbrumann Avatar answered Aug 01 '26 10:08

dbrumann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!