10.

A non well formed numeric value encountered

編集
この記事の要点
  • PHP の A non well formed numeric value encountered (Warning)
  • 原因: 数値に変換できない文字列を算術演算に使っている(例: "10abc" + 5
  • 対処: 明示キャスト (int)$v / (float)$v または intval() / floatval()
  • PHP 8 では同じ条件で TypeError になることがあるので注意

 

エラー内容

A non well formed numeric value encountered

PHP 7.1 以降で、数値として扱えない文字列を算術演算に使ったときに表示される Warning です。PHP 8 ではより厳しくなり、完全に数値でない文字列を渡すと TypeError になる場合があります。

発生条件 / 原因

  • 数値に変換できない(先頭が数値だが末尾に非数字が含まれる)文字列を四則演算の対象にしたとき
  • 例: "10abc" + 5 → 値は 15 になるが Warning が出る
  • 例: "1.5kg" * 2 → 値は 3 になるが Warning
  • DBから取得した値、HTTPリクエストパラメータ、CSV読み込みなど、外部からの文字列を直接演算しているケース
  • 日付の差分計算で "2024-01-01" をそのまま演算した

対処法

1. 明示的に数値型へキャストする

$result = (int) $value + 5;
$result = (float) $value * 2;

2. intval() / floatval() を使う

$result = intval($value) + 5;
$result = floatval($value) * 2;

どちらも先頭から読み取れる数値部分のみ取り出し、警告は出しません。

3. 事前にバリデーションする

入力値が想定外の文字列の場合は弾く方が安全です。

if (!is_numeric($value)) {
    throw new InvalidArgumentException('numeric required');
}
$result = $value + 5;

4. Laravel等のフレームワーク

Laravelなら request()->integer('key') や Validation の numeric ルールで入力時に型を保証できます。

$request->validate(['qty' => 'required|integer|min:1']);
$qty = $request->integer('qty');

PHPバージョン別の挙動

PHPバージョン挙動
PHP 7.0以前警告なしで暗黙変換
PHP 7.1 – 7.4「A non well formed numeric value encountered」Warning
PHP 8.0以降部分数値はWarning、完全に非数値はTypeError

注意点

  • Warning なので動作自体は継続するが、本番ログを汚すので必ず対応する
  • PHP 8 への移行時にこの警告が TypeError に格上げされて落ちるケースがある
  • error_reporting で抑制するのではなく、入力値を正しい型にする方向で直す
編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. Fatal error: Maximum execution time of 30 seconds exceeded in...
  2. Fatal error: Uncaught Error: Cannot use object of type stdClass as array in ...
  3. Warning: Use of undefined constant ... - assumed '...' (this will throw an Error)
  4. ERROR: Call to undefined method Maatwebsite\Excel\Excel::load()
  5. Maximum execution time of 30 seconds exceeded
  6. Your requirements could not be resolved to an installable set of packages. ... To enable extensions, verify that they are enabled in your .ini files:
  7. could not find driver
  8. the requested PHP extension mbstring is missing from your system.
  9. the requested PHP extension dom is missing from your system.
  10. A non well formed numeric value encountered
  11. Warning: Cannot modify header information - headers already sent by ...
  12. php_network_getaddresses: getaddrinfo failed: Name or service not known
  13. XMLWriter::openUri(): Unable to resolve file path
  14. Object of class stdClass could not be converted to string
  15. Class 'Google_Service_Youtube' not found