ctype_digit

数字かどうかを調べる

説明

bool ctype_digit(mixed $text)

与えられた文字列 text のすべての文字が 数字であるかどうかを調べます。

パラメータ

text

調べる文字列。

注意:

-128 から 255 までの int を渡すと、ひとつの文字の ASCII 値とみなします (負の値には 256 を足して、拡張 ASCII の範囲に収まるようにします)。 それ以外の整数値は、10 進数を含む文字列とみなします。

警告

PHP 8.1.0 以降は、ctype関数 に文字列でない引数を渡すことは、推奨されなくなりました。将来のバージョンでは、引数は ASCII コードポイントではなく、文字列として解釈されるようになります。ユーザが意図する振る舞いによっては、引数を文字列にキャストするか、 chr を明示的にコールすべきです。

戻り値

string text のすべての文字が 10 進数字だった場合に true、そうでない場合に false を返します。 空文字列を渡して呼び出した場合、結果は常に false になります。

例1 ctype_digit の例

<?php
$strings 
= array('1820.20''10002''wsl!12');
foreach (
$strings as $testcase) {
    if (
ctype_digit($testcase)) {
        echo 
"The string $testcase consists of all digits.\n";
    } else {
        echo 
"The string $testcase does not consist of all digits.\n";
    }
}
?>

上の例の出力は以下となります。

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

例2 ctype_digit で文字列と整数値を比較する例

<?php

$numeric_string 
'42';
$integer        42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 は * です)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

参考

  • ctype_alnum
  • ctype_xdigit
  • is_numeric
  • is_int
  • is_string
  • IntlChar::isdigit