我有这个脚本:
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
//=> no
演示
为什么打印no
?我希望它打印yes
。因为$id
的值始于0
。怎么了?
编辑:实际上我是这样的$id
:DecryptId($_POST['au']);
。$_POST['au']
包含一个数字。这样的东西:
23
43552
0153
314
09884
如您所见,有时该数字以0
开头。我需要将其作为字符串传递。我该怎么做?
由于领先的零,PHP将以八分音为单位。即使没有这样做,大多数语言都会剥离领先的零(因为它们实际上并未构成数字的一部分)。这意味着$id
将对12
进行评估。
您确定不想将其声明为字符串吗?($id = "014"
)
您的功能正常工作。问题是,当您应该提供字符串时,您正在函数中传递一个数字。因此,在您的变量类型为integer
的情况下,领先的零将最终 fly ake。
您可以将一些内容添加到您的功能中以检查变量类型并通知用户。
function DecryptId($id) {
$type = gettype( $id );
if($type!= "string") {
echo "Your variable has type ".$type.". Use a 'string' type variable";
return;
}
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
echo "n";
$id = '014';
echo DecryptId($id);
尝试以上示例php sandbox
尝试此
<?php
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = '014';
echo DecryptId($id);
?>