LoginSignup
1
1

More than 1 year has passed since last update.

【PHP】数値じゃない要素にintvalをかけるとエラーが出ると思っていた

Last updated at Posted at 2022-04-12

こういう処理を書いた時、数値じゃない文字は整数に出来ないからエラーを吐くんじゃないかと思ってたんですが、

$hoge = ['あ','い','う'];
$huga = null;
try {
  $huga = array_map('intval', $hoge);
} catch (\Throwable $exception) {
  dd($exception);
}
dd($huga);

出力結果、エラーになりませんでした。
image.png

PHP公式ドキュメント:intval

成功時は value の整数値、失敗時は 0。 空の配列の場合は 0、空でない配列の場合は 1 を返します。

数値以外の文字列が入っていないか検知したければis_numericとかを使ってチェックしましょうという事ですね

 
PHP公式ドキュメント:is_numeric

value が数値または 数値形式の文字列 である場合に true、それ以外の場合に false を返します。

$hoge = (int)'hoge';

のようにキャストした場合も0で出力されたので少しびっくり、言語仕様あまり知らないまま使っていたのでちょっと怖いです

1
1
0

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