Why is this not working? please t...">

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.

+4
source share
3 answers

There are two problems in your code.

At first, single quotes ( ' ) behave differently than a string with two quotes ( " ). When using strings with single quotes, escape sequences (except \' and \\ ) are not interpreted, and variables are not consumed. This can be fixed as such ( removing quotes or changing them to double quotes):

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

PHP documentation: lines


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

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

!== FALSE important in this case, since 0 also evaluates to FALSE . This means that if you delete !== FALSE , your first character will not be output.

PHP documentation: strpos()
PHP Documentation: Boolean Conversion
PHP Documentation: Comparison Operators

+22
source

It’s only you don’t see anything, because:

 'hey' != '$i' 

Also, if your $ i was not in single quotes (which makes its value "$ i" literally)

 'hey' != 'a'; 'hey' != 'b'; 'hey' != 'c'; ... 'hey' != 'z'; 
+2
source

Instead of testing ==, look at the strspn () function

0
source

Source: https://habr.com/ru/post/1301216/


All Articles