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
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:-
https://eval.in/989587
https://eval.in/989588
https://eval.in/989593
https://eval.in/989596
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With