skip to Main Content

I have an array and loop like this:

<?php 
  $letters = array("a", "b", "aa", "c", "bb", "bcb");
  foreach( $letters as $letter ){
    echo "$letter <br />";
  }
?>

I’m getting all value from here.

But I just need that value whose first letter is ‘B’.
How can I get it please help me?

2

Answers


  1. Select first char of $letter by suing substr, then compare by b.

    Note: change case to lower for support b and B

    $letters = array("a", "b", "aa", "c", "bb", "bcb");
    foreach ($letters as $letter)
    {
        if (strtolower(substr($letter, 0, 1)) != 'b')
        {
            continue;
        }
    
        echo "$letter <br />";
    }
    
    Login or Signup to reply.
  2. Based on @Lessmore’s answer, but reducing a few things.

    You don’t need to do substr() for 1 character, you can just use the idea of using a string as an array and use $letter[0].

    I’ve also changed the condition so that it checks === b, so this saves having a continue and just does the processing in the if instead.

    $letters = array("a", "b", "aa", "c", "bb", "bcb");
    foreach ($letters as $letter)
    {
        if (strtolower($letter[0]) === 'b')
        {
             echo "$letter <br />";
        }
       
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search