3

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 
mileven
  • 204
  • 3
  • 13

2 Answers2

2

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.

dbrumann
  • 16,803
  • 2
  • 42
  • 58
2

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98