ballouta Posted May 30, 2009 Share Posted May 30, 2009 Hello, I am trying to read the first letter of all members in a table, then store them in an Array with duplications, but the problem is that the letters are stored duplicated when i print the array the end. my code: <?php $ltr = array ('m'); //this is my username $query = "SELECT * FROM members "; $result = mysql_query($query) or die (mysql_error()); while( $row = mysql_fetch_array($result)) { $rest = substr("$row[usernme]", 0, 1); //this read the 1st letter of each username //echo "Rest = $rest <br>"; this is working //check if this letter exists in the array, No duplications allowed foreach ($ltr as $show) { if ($show != $rest) {$ltr[] = $rest; echo "$rest added<br>";} //ballouta else {} }//foreach }//end while foreach ($ltr as $show) { echo "$show /"; } ?> i added the echo line to check if if is entering to that scope, and it really show that it is adding it many times, Please help Many thanks Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted May 30, 2009 Share Posted May 30, 2009 SELECT DISTINCT SUBSTRING(username, 1, 1) AS firstLetter FROM members; Quote Link to comment Share on other sites More sharing options...
Garethp Posted May 30, 2009 Share Posted May 30, 2009 Why not store the first letter as the key of the array? That way, it can't make duplicates, like this kinda $Array[$Firstetter] = 1; foreach($Array as $k => $v) { echo $k . "<br>"; } Quote Link to comment Share on other sites More sharing options...
MadTechie Posted May 30, 2009 Share Posted May 30, 2009 SELECT SUBSTRING(`UserName`,1,1) as letter FROM `users` GROUP BY letter $result = mysql_query($query) or die (mysql_error()); $letters = array(); while( $row = mysql_fetch_array($result)) { $letters[] = $row['letter'] } Edit: never mind lol Quote Link to comment Share on other sites More sharing options...
ballouta Posted May 30, 2009 Author Share Posted May 30, 2009 Thank you ALL ur code is working Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.