user3416706
user3416706

Reputation:

How to echo duplicate lines only one time in for loop?

I have coded this :

<?php

    $onlinecheck = mysql_query("SELECT * FROM online  order by id DESC");
   for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++)
{   
$page               = $onlinecheck1->page;




echo $page;
}

?>

and my table is like this :

1  index.php
2  index.php
3  contact.php
4  gallery.php

It will be printed as like this :

   index.php
   index.php
   contact.php
   gallery.php

But i want to print like this :

   index.php
   contact.php
   gallery.php

Help me please

Upvotes: 0

Views: 1061

Answers (2)

Barmar
Barmar

Reputation: 780929

Make an associative array whose keys are the names you've printed. Before printing a name, check whether it's already in the array.

$pages_printed = array();
for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++)
{   
    $page = $onlinecheck1->page;
    if (!isset($pages_printed[$page])) {
        $pages_printed[$page] = true;
        echo $page;
    }
}
//I have added missed > )

Upvotes: 1

martin-georgiev
martin-georgiev

Reputation: 41

<?php

    $onlinecheck = mysql_query("SELECT * FROM online  order by id DESC");
    if ($onlinecheck) {
        $used = array();
        for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++) {   
            $page = $onlinecheck1->page;
            if (!isset($used[$page]) || $used[$page] !== true) {
                $used[$page] = true;
                echo $page;
            }
        }
    }

?>

Upvotes: 0

Related Questions