0

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

$implode1 = "cat, dog, chicken";

$implode2 = "cow, goat, cat";

If the cat in the variable $implode1 is also contained in the variable $implode2, it should display a warning message. How to code for the above problem?

Help me please :(

2
  • So you only want to enter unique items? Commented Nov 9, 2012 at 8:39
  • Better idea will be truncate all the occurencce of the string except one instead of throwing warning. Commented Nov 9, 2012 at 8:49

5 Answers 5

2

You could explode your strings to arrays, then use array_intersect to return the values which are present in both, eg:

$string1 = 'cat, dog, chicken';
$string2 = 'cow, goat, cat';

$compare = explode(', ', $string1);
$against = explode(', ', $string2);

$matches = array_intersect($compare, $against);
Sign up to request clarification or add additional context in comments.

Comments

2
$implode1 = "cat, dog, chicken";
$implode2 = "cow, goat, cat";

$imp1 = explode(', ',$implode1);
$imp2 = explode(', ',$implode2);

foreach($imp1 as $val){
    if(in_array($val,$imp2)) {
        echo "$val is present in $implode2";
    }
}

Comments

0

loop the first array and check if any element is present in the second - something like this:

foreach($implode1 as $val){
if(in_array($val,$implode2)) {

    echo "$val is exists in the implode2 array";

       }
}

ohh, sorry, those are just strings. First explode them:

arr_implode1 = explode(", ",$implode1)
arr_implode1 = explode(", ",$implode2)

Comments

0

You could just check before inserting the values into a database if they already exist:

if not exists (select * from TestTable where column NOT IN {$implode})
begin
    ...Do something here!!
end

Comments

0

Create yourself a function that is able to extract the values out of each string in form of an array, then get the intersection. If it is not FALSE, there is an intersection, so do the warning:

$values = function($string) {
    return explode(', ', $string);
};

if (array_intersect($values($implode1), $values($implode2))) {
    trigger_error('Values intersect', E_USER_WARNING);
}

See it in action.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.