[PHP-users 23526]foreach関数の挙動について

masahide86 @ hotmail.com masahide86 @ hotmail.com
2004年 10月 30日 (土) 04:12:57 JST


はじめまして 山本といいます。

これはforeach関数の挙動とは関係ないと思われます。

PHPのマニュアルに下記の記述がありました。

具体的には、phpでは「数値ともとれる文字列を数値として」、また、「数値とは取
れない文字列を0として」 比較演算子のコンテキストで処理しようとするようで
す。

したがって、"0"は0と評価され、数値との比較なので、"abc"も0と評価されることに
よって、このような振る舞いになるものと思われます。

詳しくは下記を。

jwhiting at hampshire dot edu
10-Dec-2003 08:31
note: the behavior below is documented in the appendix K about type
comparisons, but since it is somewhat buried i thought i should raise it
here for people since it threw me for a loop until i figured it out
completely.

just to clarify a tricky point about the == comparison operator when dealing
with strings and numbers:

('some string' == 0) returns TRUE

however, ('123' == 0) returns FALSE

also note that ((int) 'some string') returns 0

and ((int) '123') returns 123

the behavior makes senes but you must be careful when comparing strings to
numbers, e.g. when you're comparing a request variable which you expect to
be numeric. its easy to fall into the trap of:

if ($_GET['myvar']==0) dosomething();

as this will dosomething() even when $_GET['myvar'] is 'some string' and
clearly not the value 0

i was getting lazy with my types since php vars are so flexible, so be
warned to pay attention to the details...


> -----Original Message-----
> From: php-users-bounces @ php.gr.jp [mailto:php-users-bounces @ php.gr.jp] On
> Behalf Of Kamata
> Sent: Saturday, October 30, 2004 4:00 AM
> To: PHP-users ML
> Subject: [PHP-users 23524]foreach関数の挙動について
>
> はじめまして、鎌田といいます。
>
> 本日、コーディング中に以下のような現象に遭遇しました。
> どう調べても挙動がおかしい気がします。
>
> 自分ではどうしても解決できなかったので、アドバイスいただけると幸いです。
>
> 例えば以下のようなプログラムを実行すると、
>
> ---ソース---------------------------------------------
> 1  $a = array("0"=>"あああ","1"=>"いいい","2"=>"ううう");
> 2  $b = "abc";
> 3
> 4  foreach ($a as $key => $value) {
> 5
> 6    if($key == $b){
> 7      echo "{$key}と{$b}は一緒<br>\n";
> 8    }else{
> 9      echo "{$key}と{$b}は違う<br>\n";
> 10   }
> 11 }
> ----------------------------------------------------
>
> 以下のように出力されます。
>
> ---出力結果-----------------------------------------
> 0とabcは一緒
> 1とabcは違う
> 2とabcは違う
> ----------------------------------------------------
>
> 6行目、$key が 0 の時に $key==$b がTRUEになる理由が分かりません。
>
> 実は、1行目を、
> $a = array("1"=>"あああ","2"=>"いいい","3"=>"ううう");
> など、0以外をkeyにして配列を作ると、予想した結果が出ることが分かったので
> すが、根本的な解決じゃない気がしてすっきりしないのです。
>
> 上記のソースを実行し、以下のような結果を出すことはできないでしょうか?
>
> 0とabcは違う
> 1とabcは違う
> 2とabcは違う
>
>
> 以上よろしくお願いいたします。
>
> ・以下の環境で試しました。
> RedHat8   Apache/1.3.27 PHP/4.3.4
> RedHatES3 Apache/2.0.50 PHP/4.3.8
> FreeBSD  Apache/1.3.29 PHP/4.2.4-dev
>
>
> 鎌田 kou @ neta.jp
> _______________________________________________
> PHP-users mailing list  PHP-users @ php.gr.jp
> http://ns1.php.gr.jp/mailman/listinfo/php-users
> PHP初心者のためのページ - 質問する前にはこちらをお読みください
> http://www.php.gr.jp/php/novice.php3




PHP-users メーリングリストの案内