LoginSignup
0
0

More than 1 year has passed since last update.

"." の扱い。

Last updated at Posted at 2023-03-29

PHP7.4 までは 「"." に 0.0を足す」といういささかアタマノワルイ^H^H^H^H^Hイレギュラーな処理について、Warningこそ出しながら、致命的な型エラーにならなかったものも、PHP8.0からは TypeError になり、通してもらえません。

test.csv


0,1,2,3,4,5,6,7,8,9,10
0 , 1 , 2 ,3 ,4 5 ,7, 9, 19
.,.,.
~

テスト環境


$ php -v
PHP 8.0.28 (cli) (built: Mar 23 2023 09:00:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.28, Copyright (c) Zend Technologies

$ ./php -v
PHP 7.4.33 (cli) (built: Mar 28 2023 16:33:02) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

テストコード



$csvfile = fopen('test.csv',"r");
while ($data = fgetcsv($csvfile,1000,",")) {
    
   $num = count ($data);
   print $num . "\n";
   for ($colmn=0;$colmn<$num; $colmn++) {
     print "0.0"+ $data[$colmn]."\n";
   }  

テスト結果

まずは、php7.4 です。


 ./php test_fgetcsv.php
11
0
1
2
3
4
5
6
7
8
9
10
8
0
1
2
3
4
7
9
19
3

Warning: A non-numeric value encountered in /usr/home/strnh/test_fgetcsv.php on line 10
0

Warning: A non-numeric value encountered in /usr/home/strnh/test_fgetcsv.php on line 10
0

Warning: A non-numeric value encountered in /usr/home/strnh/test_fgetcsv.php on line 10
0

ワーニングが出るだけでとりあえず "." を 0と認識します。

PHP8.0ではどうでしょうか:


 php ./test_fgetcsv.php 
11
0
1
2
3
4
5
6
7
8
9
10
8
0
1
2
3
PHP Warning:  A non-numeric value encountered in /usr/home/strnh/test_fgetcsv.php on line 10
4
7
9
19
3
PHP Fatal error:  Uncaught TypeError: Unsupported operand types: string + string in /usr/home/strnh/test_fgetcsv.php:10
Stack trace:
#0 {main}
  thrown in /usr/home/strnh/test_fgetcsv.php on line 10

結論

もはや型変換が厳しく、変なデータを喰わせたときの挙動が明らかにゲキオコです。
0.0 + というやり方が悪いのか。

"." という表現を 0.0 であるとする古いcsvファイルを読み込ませるときにトラブルが発生します。混ざっている " " 空白については 文句をいうだけで、とりあえずパースはしてくれます。

文字列から数値に変換する際の細工がもう少し必要なのでしょう。

以上

0
0
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
0
0