如何在php循环中检测a-z字母? [关闭]

I want to detect starting letter of string A-Z

Currently I am displaying data using loop which displays data from a to z

Now I want to detect data starting with letter "a" in loop

Is that possible using PHP?

I want same this http://cdn.ihwy.net/ihwy-com/labs/demos/jquery-listnav.html using PHP

Actually I want to add "Clear" name class after printing "a" letter data and so on for every letter (b,c,d.....z)

This should work if all of the categories are stored in an array

//Define the first letter that you want to focus on
$letter = 'b';

//Store all items in an array
$categories = array('Books', 'Marketing', 'TV', 'Radio', 'Computers');

//Loop thru
for($i=0;$i<count($categories);$i++)
{
    //This might be case sensitive, so lower the items and get the first letter of it
    if(strtolower(substr($categories[$i], 0, 1)) == $letter)
    {
         echo $categories[$i].'<br />';
    }
}

OR, if you're storing all of them in MySQL

//Connect to MySQL
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
//Query the DB for all categories beginnng with a particular letter
$query = "SELECT * FROM table WHERE category LIKE '".$letter."%'";
$result = mysqli_query($link, $query);
$count = mysqli_num_rows($result);
$i = 0;

while ($row = mysqli_fetch_assoc($result)) {
  $categories[$i] = $row['category'];

  $i++;
}

//Loop thru
for($i=0;$i<$count;$i++)
{
   echo $categories[$i].'<br />';
}

You produce the exact same effect that's shown on the link you provided, you'll need more than just PHP; you'll need JS too. But, that's another task.

Yes there are several ways, a really simple one is to just check the first letter in the string:

foreach($lines as $line) {
    if($line[0] == "a") {
        echo $line
    }
}

If you want to be a bit more fancy you can do the same by using preg_match:

foreach($lines as $line) {
    if(preg_match("/^a.*/", $line) {
        echo $line
    }
}

If you are using a storage engine like MySQL you should sort the data before the results, e.g:

SELECT * FROM table WHERE name LIKE 'a%'

If you are using memory you probably want to use some sort of a filter function:

$a = [];
foreach ($data as $i => $v)
    if ($v{0} == "a") $a[] $v;

// $a now contains everything on a*

Sorting the results:

natsort($a);