PHP_Newbie
PHP_Newbie

Reputation: 79

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.

Upvotes: 7

Views: 19998

Answers (4)

Thomas Lauria
Thomas Lauria

Reputation: 908

Or just do it by string increment:

$x = 'A';
for($i=0; $i < 30; $i++){ 
  echo $x++;
  echo "; "; 
}

gives

A; B; C; D; E; F; G; H; I; J; K; L; M; N; O; P; Q; R; S; T; U; V; W; X; Y; Z; AA; AB; AC; AD; 

Upvotes: 0

Andrew Moore
Andrew Moore

Reputation: 95334

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

Upvotes: 26

Kami
Kami

Reputation: 6059

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

Upvotes: -1

meouw
meouw

Reputation: 42140

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';

Upvotes: 3

Related Questions