How do I code something to appear alphabetically from list of links A B C D E...etc?

Hi

What is the PHP code for getting information to appear based upon the letter of the alphabet clicked?

i.e. if you click A you get all records starting with A, if you click G you get all records starting with G

If the links are A B C D E F G etc

and the data is

Cats
Dogs
Zebra
Deer

how do I make “dogs” and “deer” appear when you click D? (What is the PHP code for the link for the letter D?)

Hope you can help,

Matt.

You’d grab the letter using the HTTP GET method, where the query string within the URI would contain the letter to search for, such as [b]http://domain.tld/page.php?letter=a[/b]

Using the $_GET super global, you could then validate the user input:


if(preg_match('#^[a-z]{1}$#i', $_GET['letter'])) {
    $letter = strtolower($_GET['letter']); // valid input
}else{
    $letter = 'a'; // default value for invalid input
}

And then depending upon where the data is coming from (a database, file, or elsewhere?), you’ll need to take the input and use it to filter the word list you have.

If it’s from a database, then you could execute a query like the following:


$q = "SELECT word FROM relation WHERE word LIKE '{$letter}%'";

If it’s from a file (which should be loaded into an array) or from an array within your PHP code, then you could use something like the following:


<?php

$letter = strtolower('b'); // from input

$words = ['cat', 'dog', 'bird', 'horse', 'blue bird'];

$validWords = array_filter($words, function($word) use ($letter) {
	if($word[0] === $letter) {
		return $word;
	}
});

var_dump($validWords);
/*
 *bird
 *blue bird
 */

A little complicated but I might be able to do a bit of reading about what you have suggested.

It would be a MySQL database (from text file) with array data. I would need to ‘get’ a link associated with (in this case) the type of animal too.

Is there not an easier method whereby I can get the animal name and link associated with it and then just ‘echo’:

<a href=echo"$link">echo$AnimalType</a>

or something very similar anyhow?

To get the link too, would I just need to write:

$r = “SELECT link FROM relation WHERE word LIKE ‘{$letter}%’”;

?

…and how should I neatly echo the information as a vertical list? Otherwise it will just be a horizontal mess, right?

And I hope the initial letter matching is not case sensitive as in most case it will be uppercase.