Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Alphabet Loop

Tags:

php

<?php
$string = 'hey';

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

Why is this not working? please tell me.

like image 590
PHP_Newbie Avatar asked Feb 13 '10 21:02

PHP_Newbie


2 Answers

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

like image 186
Andrew Moore Avatar answered Oct 23 '22 18:10

Andrew Moore


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';
like image 45
meouw Avatar answered Oct 23 '22 17:10

meouw