Php Alphabet Loop

前端 未结 3 1500
日久生厌
日久生厌 2021-01-18 09:01

Why is this not work

相关标签:
3条回答
  • 2021-01-18 09:39

    You have two problems in your code.

    First, single-quotes strings (') behave differently than double-quotes string ("). When using single-quotes strings, escape sequences (other than \' and \\) are not interpreted and variable are not expended. This can be fixed as such (removing the quotes, or changing them to double-quotes):

    $string = 'hey';
    
    foreach(range('a','z') as $i) {
      if($string == $i) {
        echo $i;
      }
    }
    

    PHP Documentation: Strings


    Secondly, your condition will never evaluate to TRUE as 'hey' is never equal to a single letter of the alphabet. To evaluate if the letter is in the word, you can use strpos():

    $string = 'hey';
    
    foreach(range('a','z') as $i) {
      if(strpos($string, $i) !== FALSE) {
        echo $i;
      }
    }
    

    The !== FALSE is important in this case as 0 also evaluates to FALSE. This means that if you would remove the !== FALSE, your first character would not be outputted.

    PHP Documentation: strpos()
    PHP Documentation: Converting to boolean
    PHP Documentation: Comparison Operators

    0 讨论(0)
  • 2021-01-18 09:44

    In place of testing == have a look on the strspn() function

    0 讨论(0)
  • 2021-01-18 09:53

    It is but you aren't seeing anything because:

    'hey' != '$i'
    

    Also if your $i wasn't in single quotes (making it's value '$i' literally)

    'hey' != 'a';
    'hey' != 'b';
    'hey' != 'c';
    ...
    'hey' != 'z';
    
    0 讨论(0)
提交回复
热议问题