Php Alphabet Loop
<?php
$string = 'hey';
foreach (range('a', 'z') as $i) {
if ($string == '$i') {
echo $i;
}
}
?>
Why is this not working? please tell me.
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
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';