Search code examples
phpserver-sideserver-side-scripting

PHP: Don't echo a variable in a while loop IF it's a duplicate


I have a variable in an SQL query-based while loop. e.g:

$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){

    echo $row['row'];

}

The while loop is functional and works, however the variable contains duplicate strings.

How do I prevent duplicate row variables echoing in my while loop with PHP?

Note: This is a PHP question, not an SQL question.


Solution

  • Just keep track of each row's unique ID. If you see again, skip it.

    $sql = mysql_query("SELECT * FROM table");
    $ids = array();
    while($row=mysql_fetch_array($sql)){
        if (!isset($ids[$row['id']])) {
            continue;
        }
        $ids[] = $row['id'];
        echo $row['row'];
    
    }
    

    FYI, this is a lot easier and faster if you do it in SQL. But if you must do it in PHP this is how you would do it.