:: Sharing tFFed mind
Апрель 22, 2024, 09:13:44 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.

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

Сообщений: 422

« : Июнь 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.


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

Вариант 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]   Вверх
Перейти в:  

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