11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPにおける加算子($i++)と代数演算子($i=$i+1)の動作の違いについて

Posted at

何となくやっていたら、どハマったのでメモ…。

PHPは演算の際に型の自動変換を行うことがあります。

PHP の自動型変換の例の一つは、代数演算子 '+' です。 オペランドのどれかが float の場合、全てのオペランドは float として評価され、結果は float になります。 その他の場合、オペランドは整数として解釈され、結果も整数になります。
(PHP: 型の相互変換 - Manual http://php.net/manual/ja/language.types.type-juggling.php

 変数内が数値のみの場合

例えば、以下のような場合、文字列型の「"0"」が演算時に自動的にキャストされ、数値型の「1」になります。
このように、変数の中身が数値のみの場合は、加算子$i++と代数演算子$i=$i+1で動作は同じです。

test.php
$str = "0";    //string(0)
++$str;          //integer(1)

$str = "0";    //string(0)
$str = $str + 1;     //integer(1)

 変数内に文字を含んでいる場合

ところが、**文字列中に数字以外の文字がある場合は、加算子$i++と代数演算子$i=$i+1で動作が異なってきます。**以下に例を示してみます。

test.php
$str = "1a";   //string(1a)
++$str;         //string(1b) 文字列型のまま

$str = "1a";   //string(1a)
$str = $str + 1;//integer(2) 数値型に変換される

すなわち、加算子$i++の場合は、文字列型のまま1つ分進めます(1aから1bに)が、代数演算子$i=$i+1はaの文字を無視して先頭の「1」だけ取り出して「2」にしています。

代数演算子はこのような場合、一番先頭の数値を取り出すようです。例えば、以下の場合は、先頭の「9」を取り出して「10」にしています。

test.php
$str = "9a1a1";   //string(9a1a1)
$str = $str + 1;//integer(10) 数値型に変換される

また、先頭が文字以外の場合は、代数演算子で演算すると、自動的に「1」になります。

test.php
$str = "a100";   //string(a)
$str = $str + 1;//integer(1) 数値型に変換される

参考:
PHP の演算子のちょっとした振る舞いの違いに要注意 | バシャログ。 http://c-brains.jp/blog/wsg/14/03/19-100000.php

PHP: 加算子/減算子 - Manual http://php.net/manual/ja/language.operators.increment.php

PHP: 型の相互変換 - Manual http://php.net/manual/ja/language.types.type-juggling.php

11
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?