Reply to Re: WTF? String = Integer in PHP? Strlen() in integers WORKS? HELP!

Your name:

Reply:


Posted by Justin Koivisto on 02/03/06 19:31

comp.lang.php wrote:
> I'm involved in a rather nasty debate involving a strange issue
> (whereby the exasperated tell me to RTFM even after my having done so),
> where this is insanely possible:
>
> [PHP]
> print_r(is_int('1')); // PRINTS NOTHING
> print_r(strlen((int)1)); // PRINTS '1'
> [/PHP]
>
> Now I understand that in PHP, everything scalar is a string and can
> take on the role of an integer, or a boolean or.. whatever it's
> configured to look like. Why is it that I'm so "way off" in this
> thread, when it seems to me that I have it right based on my basic
> understanding the definition of "types"?
>
> Phil
>
> http://phpbuilder.com/board/showthread.php?t=10316949

strlen() expects a string as a parameter. because of the "typeless"
nature of PHP, when something other than a string is sent, PHP will
automatically "cast" it to a string (like using the strval() function).
Therefore, when the length is calculated, it is operating on the
equivalent to $int = strval($int) instead of the actual integer.

The same type of thing happens when using expressions:

('1' == TRUE) will result in a bool(true). This is because the lowest
common type between string and bool is bool (the simplest of all).
Therefore, the string is cast to a boolean val, then the comparison is made.

Consider var_dump('my string'==1). This returns bool(false) because the
string is cast to an integer (the simplest common type) which is 0.

In constrast, var_dump('1 string'==1) return bool(true) because the
intval('1 string') === 1


The type Juggling section of the manual is about the best reference you
can use for this kind of thing, but IMO it isn't nearly as complete as
it could be for a novice level explanation.

http://us2.php.net/manual/en/language.types.type-juggling.php

--
Justin Koivisto, ZCE - justin@koivi.com
http://koivi.com

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация