PHPでの数値文字列の扱い
- php
- | トラックバック(0)
- | コメント(1)
PHPでの数値文字列の扱いはとっても微妙。便利だなと思うときもあれば、危険だなと思うときもある。
以下のようなスクリプトを使ってテストしてみると…
<?php
$test = $_POST["test"];
// データ型を文字列に指定
settype($test, "string");
// 数字として扱ってくれる?
if(is_numeric( $test )) $numeric = "数字でっせ!";
else $numeric = "数字じゃね〜よ!";
// 数字として扱ってくれる?
if(ctype_digit( $test )) $digit = "数字でっせ!";
else $digit = "数字じゃね〜よ!";
// 文字列に足してみる
$test_plus = $test + 3;
//テスト
echo <<<EOF
<html>
<head>
<title>テスト</title>
</head>
<body>
test = $test<br>
numeric = $numeric<br>
digit = $digit<br>
test_plus = $test_plus<br>
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="text" name="test" size="20">
<input type="submit" value="送信">
</form>
</body>
</html>
EOF;
?>
//******** 結果 *********
入力:0 結果:test = 0, numeric = 数字でっせ!, digit = 数字でっせ!, test_plus = 3
入力:3 結果:test = 3, numeric = 数字でっせ!, digit = 数字でっせ!, test_plus = 6
入力:1.2 結果:test = 1.2, numeric = 数字でっせ!, digit = 数字じゃね〜よ!, test_plus = 4.2
入力:a 結果:test = a, numeric = 数字じゃね〜よ!, digit = 数字じゃね〜よ!, test_plus = 3
結果を見て分かるとおり、わざわざ「文字列」と指定しても数字の文字列なら「数字」と解釈されるし、計算もできてしまう。
以下のようなスクリプトを使ってテストしてみると…
<?php
$test = $_POST["test"];
// データ型を文字列に指定
settype($test, "string");
// 数字として扱ってくれる?
if(is_numeric( $test )) $numeric = "数字でっせ!";
else $numeric = "数字じゃね〜よ!";
// 数字として扱ってくれる?
if(ctype_digit( $test )) $digit = "数字でっせ!";
else $digit = "数字じゃね〜よ!";
// 文字列に足してみる
$test_plus = $test + 3;
//テスト
echo <<<EOF
<html>
<head>
<title>テスト</title>
</head>
<body>
test = $test<br>
numeric = $numeric<br>
digit = $digit<br>
test_plus = $test_plus<br>
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="text" name="test" size="20">
<input type="submit" value="送信">
</form>
</body>
</html>
EOF;
?>
//******** 結果 *********
入力:0 結果:test = 0, numeric = 数字でっせ!, digit = 数字でっせ!, test_plus = 3
入力:3 結果:test = 3, numeric = 数字でっせ!, digit = 数字でっせ!, test_plus = 6
入力:1.2 結果:test = 1.2, numeric = 数字でっせ!, digit = 数字じゃね〜よ!, test_plus = 4.2
入力:a 結果:test = a, numeric = 数字じゃね〜よ!, digit = 数字じゃね〜よ!, test_plus = 3
結果を見て分かるとおり、わざわざ「文字列」と指定しても数字の文字列なら「数字」と解釈されるし、計算もできてしまう。
- [2006/01/27 12:45]
- php |
- トラックバック(0) |
- コメント(1)
- この記事のURL |
- TOP ▲
コメント
PHPの勉強を始めようかと
SNSサイトの開発は、もっぱらPerlで行っているのですが、一部フリーのソフトを組み込むため(そのソフトがPHPなのです)勉強しようかと思っています。(来年の後半ですかね)
トラックバック
この記事のトラックバックURL
http://shotets.blog21.fc2.com/tb.php/25-aa26ad6c
- | HOME |


コメントの投稿