Home > Back-end >  Search item in array in php
Search item in array in php

Time:12-29

I have the following script where I'm checking/matching items between two array. If 2nd array contains different item then return false;

$requiredString = [
    "string1",
    "string2",
    "string3",
    "string4",
    "string5"
];

$receivedString = [
    "string1",
    "string2",
    "string3",
    "string4",
    "testString7"
];
foreach ($receivedString as $key => $value) {
    if (!in_array($value, $requiredString)) {
        return false;
    }
}
return true;

The script works good but I want to refactor the script. I.E make short or decrease execution time.

Is there a possible way to refactor the script ?

CodePudding user response:

you can use array_diff function :

return empty(array_diff($requiredString, $receivedString));

CodePudding user response:

Try this:

<?php
  $arr1 = [
    "string1",
    "string2",
    "string3",
    "string4",
    "string5"
];
  $arr2 = [
    "string1",
    "string2",
    "string3",
    "string4",
    "testString7"
];
 
  // Sort the array elements
  sort($arr1);
  sort($arr2);
 
  // Check for equality
  if ($arr1 == $arr2)
      echo "Both arrays are same\n";
  else
      echo "Both arrays are not same\n";
  •  Tags:  
  • php
  • Related