tFF.msk.ru :: Sharing tFFed mind
Апрель 29, 2024, 01:19:04 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.

Войти
Новости: Пропал ребенок. Вся информация и фотографии здесь.
 
   Начало   Помощь Поиск Войти Регистрация  
Страниц: [1]   Вниз
  Печать  
Автор Тема: Особенности PHP при работе со строками  (Прочитано 3843 раз)
0 Пользователей и 1 Гость смотрят эту тему.
tFF
Administrator
Sr. Member
*****
Offline Offline

Сообщений: 422



WWW
« : Июнь 12, 2010, 17:35:57 »

Для иллюстрации особенности PHP при сравнении строк попробуйте выполнить
Код:
for ($i='a';$i<='z';$i++) echo $i.' ';
Сразу скажу, оно не выведет вопреки ожиданиям символы от A до Z.

Почему? Вот объяснение от Rasmus Lerdorf (создатель PHP):
Цитировать
tedd wrote:

Цитировать
    But, what brothers me about the routine, is that is DOES print "z" where it is supposed
    to. In other words, the characters a-z are output before continuing with aa and so on. The
    operation doesn't end with "z".

Your condition for the loop to continue is $i<="z".

When $i = "y" it will obviously continue because "y" < "z"
When $i = "z" it will obviously continue because "z" = "z"
When $i = "aa" it will obviously continue because "aa" < "z"


It doesn't stop until you get to "z"+something. As in "za" because at that point "za" > "z" so the last thing you see is the one before "za" which would be "yz".

Цитировать
    Here's another way to look at it. All characters before "z" are less than "z" -- correct? So, what
    value are all characters after "z" (i.e., "aa-yz")? They cannot be greater than, nor can they be
    less than. So, what are they?

But you are not comparing things in the same context here. Strings are naturally compared alphabetically while you are thinking they are compared numerically somehow. Think of sorting a set of words. Would you expect "aa" to sort before or after "z" ?

So yes, like I said, it is a bit of a quirk, but there is no good answer to what "z"++ should be and we certainly don't want to change the default comparison mechanism to not compare strings alphabetically because that would screw up all sorts of stuff including usorts and peoples' expectations. It's just in this case where you have gotten it into your head that incrementing strings is a good thing to do.

You'd be much better off with a range call to quickly generate a range of characters. You could then loop through that character by character. Or use the chr() function to work with character codes instead.

-Rasmus



Правильно надо делать так:

Вариант 1:
Код:
        for ($i = ord("a"); $i <= ord("z"); $i++)
        {
                echo chr($i);
        }

Вариант 2 (более наглядный и короткий):
Код:
foreach ( range('a', 'z') as $i) echo $i.' ';
« Последнее редактирование: Июнь 12, 2010, 17:48:09 от tFF » Записан

So it goes...
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  

 ONLINECHANGE
Powered by MySQL Powered by PHP Powered by SMF 1.1.4 | SMF © 2006-2007, Simple Machines LLC Valid XHTML 1.0! Valid CSS!


Google visited last this page Сентябрь 20, 2018, 18:41:01