-4

I wanted to check to enter data into the database.Checks are as follows

$implode1 = "apple, orange, banana";

$implode2 = "banana, mango";

If the banana in the variable $implode1 is also contained in the variable $implode2, it should display a warning message. and if the value of the variable is empty, then the execution will be ignored. example:

$implode1 = "";

$implode2 = "";

How to code for the above problem?

Help me please :(

user1798945
  • 145
  • 1
  • 2
  • 7

4 Answers4

0
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";

$implode1Array = explode(", ", $implode1);
$implode2Array = explode(", ", $implode2);

$result = array_intersect($implode1Array, $implode2Array);

if(count($result) > 0) {
    exit('Error!');
}
Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74
0

Typically I would assume that by cat you mean concatenation, but it doesn't seem proper here. But, assuming that is what you mean, you would just check for the same concatenation character (a comma) in both variables, like so:

if ( stristr($implode1, ",") && stristr($implode2, ",") ) {
    // error
} else {
    // success, do something
}

However, assuming you mean the same item being entered in both variables, in this case fruit, you can check it this way:

$im1 = explode(",", $implode1);
$im2 = explode(",", $implode2);
foreach($im1 as $i) {
    if ( array_search($i, $im2) ) {
        // error
    } else {
        // success, do something
    }
}

You could of course just search both strings for a given value, but I don't think that's what you're going for. But assuming it is, here is that code:

$duplicate = "apple"; // the item you are searching for a duplicate of
if ( stristri($implode1, $duplicate) && stristr($implode2, $duplicate) ) {
    // error
} else {
    // success, do something
}
SISYN
  • 2,209
  • 5
  • 24
  • 45
0
if (count(array_intersect)) { /* warning */ }
Shoe
  • 74,840
  • 36
  • 166
  • 272
0

You can use PHP's array_intersect function to get the intersection (see http://php.net/manual/en/function.array-intersect.php):

$arr1 = explode(", ", "apple, orange, banana");
$arr2 = explode(", ", "banana, mango");
$intersection = array_intersect($arr1, $arr2);
if (count($intersection) > 0) {
    echo "WARNING: the lists have a non-empty intersection!";
}
Botond Balázs
  • 2,512
  • 1
  • 24
  • 34