0

I wrote this simple code which outputs first letters of values (in this case names of companies) stored in every each table row:

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

while ($row = mysql_fetch_array($result)) {
$letter = substr($row[0], 0, 1);     
echo '<p><a href="#">' . $letter . '</a>/p>';
} 

The companies table contains names of companies and the $letter variable contains first letter of those names.

Apparently in the companies table there are many names starting with the same letter.

Now, how to display only one letter "A", one letter "B", one letter "C" etc. out of many letters "A", "B", "C" etc.?

3
  • Do you want to show each letter of the alphabet even if there isnt a company that starts with that letter? Commented Jan 2, 2014 at 10:59
  • Keep track of first letters in an array & than cross check & continue if its already exists in it. Commented Jan 2, 2014 at 11:00
  • @SubstanceD The idea was to show only letters of actually existing names. So if there is no company which names starts with A then there no A letter is shown. Commented Jan 2, 2014 at 11:13

3 Answers 3

4

Why don't you put that in your query itself?

Modify the query to

SELECT distinct SUBSTRING(Name,1,1) FROM company ORDER BY SUBSTRING(Name,1,1)

Here's the sql fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I wanted to do it in PHP but this solves my issue anyway.
@user3153286 can you mark it correct if it has solved your problem?
0

To do this in PHP you can create a blank array and push the first letter of each company onto the array if it doesnt already exist like this:

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

$letters = array();

while ($row = mysql_fetch_array($result)) {
    if(!in_array(substr($row[0], 0, 1), $letters)){
        array_push($letters, substr($row[0], 0, 1));
    }    
} 

foreach($letters as $l){
    echo '<p><a href="#">' . $l . '</a></p>';
}

If you want to show all letters of the alphabet even if a company doesnt start with that letter you can use the PHP range function like this:

foreach (range('a', 'z') as $letter) {
    echo '<p><a href="#">' . $letter . '</a></p>';
}

Comments

0

Use this SQL statement

SELECT DISTINCT SUBSTR(Name,1,1) FROM companies ORDER BY Name;

This will return distinct values from first letter of Names;

Comments

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.