0

I tried this code to get all values from a table "Contact" and then only print each value that's repeated once for example: if groups has the values (A, A, A, B, C) it will only print each one once (A, B, C) and assign each on of the those A, B, C to a new array

$sql = "SELECT Groupss FROM Contact";
$result = $conn->query($sql);
$Grouplist = array();
if (mysqli_num_rows($result) > 0) {
    while ($row = $result->fetch_assoc()) {
        $Grouplist[0] = $row;
        (array_unique($Grouplist[0]));
        foreach ($row as $key => $value) {
            $newarray[] = $value;
            echo  $value;
        }
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • `array_unique` would work, except [the documentation shows](https://www.php.net/manual/en/function.array-unique.php) that you need to assign the return value to a variable like `$unique = array_unique($Grouplist[0]);`. Though maybe you'd want to first get all of the results in the `while` loop, and then after the `while` loop then call $unique = array_unique($Grouplist);` and the iterate over `$unique`. – WOUNDEDStevenJones Jan 25 '22 at 14:43
  • If you wanted to implement this logic in PHP instead of SQL, you can get rid of the `while` loop and instead call [`$unique = array_unique($result->fetch_all(MYSQLI_ASSOC));`](https://www.php.net/manual/en/mysqli-result.fetch-all.php) to get all rows as an associative array, and then iterate over that unique result set like `foreach ($unique as $key => $value) { echo $value; }` – WOUNDEDStevenJones Jan 25 '22 at 14:50

1 Answers1

0

You could use DISTINCT which only returns distinct (different) values.

So your $sql variable would be $sql = "SELECT DISTINCT Groupss FROM Contact";

More information about DISTINCT can be found here.

Kevin
  • 1,068
  • 5
  • 14
  • 16