0

I'm trying to echo keywords from a MySQL database, separated by colon, and remove (don't show) duplicates.

This is what I got.

Keywords in DB

Love:Sorrow:Death
Happiness:Love:Excitement
Excitement:Speed:Love

PHP

<?php
$myKeyArr = array();
while($rowKeyword = mysqli_fetch_array($sqlKeyword)){
  $myKeywords = explode(':', $rowKeyword['keywords']);
  $myKeyArr[] = $myKeywords;
}

foreach ($myKeyArr as $value) {
  $kw = array_unique($value);
  echo $kw['0'] . "<br>";
}
?>

I just want to echo the following

Love
Sorrow
Death
Happiness
Excitement
Speed

This is what's shown

Love
Sorrow
Death
Happiness
Love
Excitement
Excitement
Speed
Love

1 Answer 1

0

update your code by following code.

    <?php
$referenceArray = array();
$myKeyArr = array();
while($rowKeyword = mysqli_fetch_array($sqlKeyword)){
  $myKeywords = explode(':', $rowKeyword['keywords']);
  $myKeyArr[] = $myKeywords;
}

foreach ($myKeyArr as $value) {
  $kw = array_unique($value);

/*
* checking refernceArray value..
* if vlaue find return empty otherwise it pusy value in array and print desire value
 */

  if (in_array($kw['0'], $referenceArray)){ 
  }
  else{
      array_push($referenceArray,$kw['0']);
      echo $kw['0'] . "<br>";
   }
}

?>

I hope it work perfectly.

1
  • That didn't work. Still showing duplicates. Maybe the keywords needs to be pushed into the array one by one, i some way? I'm not sure exploding them, in the db while loop, is the correct way? Commented Dec 14, 2021 at 14:57

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.