santa
santa

Reputation: 12512

Array keys starting with characters

I have an array with terms and definitions:

$myArray = array("apple" => "Fruit that grows ...", "car" => "Vehicle on four...");  

How do I determine if I have words starting with a particular letter in $myArray, say, "c" for car and add a class to corresponding letter in my ABC list that is generated via a loop:

foreach(range('A','Z') as $i) {
    echo '<div>'. $i .'</div>';
}

UPDATE:

Expected output:

<div class="match">A</div>
<div>B</div>
<div class="match">C</div>

Upvotes: 0

Views: 184

Answers (4)

imkingdavid
imkingdavid

Reputation: 1389

$myArray = array('a' => 'dog', 'b' => 'cat');
// For each letter from A to Z, contained in $i
foreach (range('A','Z') as $i) {
    echo '<b>' . $i . '</b><br />'; // Output the letter

    // For each key/value pair of the array
    foreach ($myArray as $key => $element) {
        // If the first letter of the key is the letter, it matches
        // This matches both upper and lowercase
        if (in_array($key[0], array($i, strtolower($i)))) {
            echo '<div class="match">' . $element . '</div><br />';
        }
    }
    echo '<br />';
}

That loops through A - Z and checks each key/value pair to see if the key begins with that letter (or its lowercase counterpart; it checks both A and a).

EDIT: Updated based on update to question

Upvotes: 0

Sven
Sven

Reputation: 70853

You need to compare whether the character you are about to output does exist as a first character in the array keys. Compared with all the other working solutions, which iterate over the whole data array over and over again, using a little preparation should make it easier and more understandable what happens.

$myArray = array("apple" => "Fruit that grows ...", "car" => "Vehicle on four...", "cat" => "Meow");

// Prepare array keys
$keys = array_keys($myArray);
array_walk($keys, function(&$key){$key=mb_strtoupper(mb_substr($key,0,1));});
array_unique($keys);

foreach (range('A','Z') as $char) {
    if (in_array($char, $keys)) {
        echo "<div class='match'>".$char."</div>";
    } else {
        echo "<div>".$char."</div>";
    }
}

Output:

<div class='match'>A</div><div>B</div><div class='match'>C</div><div>D</div><div>E</div><div>F</div> ...

Upvotes: 1

Teena Thomas
Teena Thomas

Reputation: 5239

Try:

$arr = array("apple" => "Fruit that grows ...", "car" => "Vehicle on four...");   
foreach ($arr as $k => $v) {
 foreach(range('a','z') as $i ) {
 if (strpos($k, $i) === 0) 
  echo "<div class='match'>". $i .'</div>';
 else
   echo '<div>'. $i .'</div>';
 }
}

Upvotes: 0

webaware
webaware

Reputation: 2841

Many ways to skin that cat. Here's one:

$matches = preg_grep('/^[A-Z]/', array_keys($myArray));
foreach($matches as $i) {
    echo '<div>'. $i .'</div>';
}

That one's case sensitive. To match A-Z and a-z, add the i modifier to the regex.

Upvotes: 1

Related Questions