Hi all,

I have been confusing myself for days over this so bear with me if it gets a bit confusing.

I have a table called tags with columns id, name which list all unique tags (linux, php, mysql, etc.). And I have an array that includes some tags that have been entered:

$tags = array('linux,php,mysql');

Now when the array has just one tag I can search the tags table and return whether the tag already exists in the table or not. But I am unsure how I can go about checking for each array item. My thinking on how to go about this (and I could be wrong) is:

  1. Explode the array.
  2. Check the first item in the array to the table.
  3. If it does not exist, put it into a separate array.
  4. Once all items have been iterated, store these unique tags in the table.

For reference, currently I have:

function tagExists($pdo, $tag) {
  $stmtTagExists = $pdo->prepare('SELECT * FROM tags WHERE name=?');
  $stmtTagExists->execute([$tag]);
  return $stmtTagExists->fetch(PDO::FETCH_ASSOC);
}

$tags = array('linux');

foreach($tags as $item) {
        if (tagExists($pdo, $item)) {
          echo 'The tag ' . $item . ' exists! <br>';
        } else {
          echo 'The tag ' . $item . ' does not exist! <br>';
        }
      }

If you need any clarification on anything, just ask.

TIA

$tags = array('linux,php,mysql');

Is an array with a single item. If linux,php,mysql is a single column in your DB, then you might do this:

$tags = explode(',', 'linux,php,mysql');

To get an array with 3 items.

commented: This helped me focus on what needed looking into. +0

I did already know how to explode an array and probably should have mentioned that, but then I thought whether you were mentioning it for a reason. So instead of just jumping all around the code wondering how to do everything, I concentrated purely on that function alone and then I was able to see the wood for the trees!

Now I have:

function remove_element($array, $value) {
  return array_diff($array, (is_array($value) ? $value : array($value)));
}

and in the tagExists if statement, I have:

$tags = remove_element($tags, $item);

And now it iterates through the array checking to see whether the item exists in the table and if it does, to remove it.

I don't know if that is how you intended to help me, but it certain did either way. Thank you :)

I don't know if that is how you intended to help me, but it certain did either way.

Probably not, but you'll find that trying to explain some problem to someone else will often help to rethink and fix the actual issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.