【问题标题】:Cast a string to an integer only if it is an integer仅当它是整数时才将字符串转换为整数
【发布时间】:2014-09-28 13:29:26
【问题描述】:
$value = "32 is my number";

if ($value == (integer) $value) {
    $value = (integer) $value; 
}

echo $value; // always 32

我了解why this does not work。仅当它实际上只是一个整数时,我将如何将字符串转换为整数?

这行得通,但它太丑了。看来应该有更好的办法:

$value = "32 is my number";
$new_value = $value;
$new_value = (integer) $new_value ;
$new_value = (string) $new_value;
if ($value == $new_value) {
    $value = (integer) $value;;
}

澄清: “32 is my number”应该是一个字符串, "32" 应转换为整数, 不应更改“32.01”。它是数字,但(整数)“32.01”变为 32

【问题讨论】:

标签: php types casting


【解决方案1】:

不知道为什么要这样做,但这会做到:

if(ctype_digit($value)) {
    $value = (int)$value;
}

编辑:从你的问题中不清楚你是否认为32 is my number 应该是一个整数:-(

【讨论】:

  • 需要这样做的原因是我正在使用一个 Web 服务,该服务期望 json 编码的整数不被我引用。我知道在最初设置变量时验证类型会更有意义,但如果没有大量重构,我无法在这个现有的代码库中做到这一点。
【解决方案2】:

有一个函数叫做is_numeric()。它测试一个字符串是否只包含数字。我认为这正是您所需要的。

if (is_numeric($value)) {
    $value = (integer) $value;
}

http://php.net/manual/de/function.is-numeric.php

【讨论】:

  • is_numeric 对我不起作用,因为浮动。 32.01 是数字,但将其转换为 int 将是 32。
【解决方案3】:

当您使用== 比较运算符时,PHP 会使用type juggling。这会导致 $value 在与 (integer) $value 进行比较之前转换为整数,从而导致它们相同。

 $value = "32 is my number";

if ($value === (integer) $value) { // $value is type juggled to 32 and then compared
    $value = (integer) $value; 
}

echo $value;

使用===比较运算符,按值进行比较类型来避免这种情况:

$value = "32 is my number";

if ($value === (integer) $value) { // $value is still "32 is my number"
    $value = (integer) $value; 
}

echo $value;

从其他答案中,您可以看到有多种方法可以做到这一点。您也可以查看 filter_var() 作为另一种选择。

$value = "32 is my number";

if (filter_var($value, FILTER_VALIDATE_INT)) { 
    $value = (integer) $value; 
}

echo $value;

【讨论】:

  • 相同比较对我不起作用,因为如果 $value 它永远不会评估为真。 ("1" === (integer) 1) 是假的,因为类型不匹配。 filter_var 会起作用。感谢您的帮助!
【解决方案4】:

您可以使用is_numeric 来确定传递的值是数字,如果是字符串则可以通过返回true 转换为数字,否则返回false

$value = "32 is numeric";
if (is_numeric(trim($value))) {
$value = (double) $value; 
echo "numeric";
}
echo $value;

【讨论】:

  • is numeric 对我不起作用,因为它会改变我的浮点数。如果值为“5.05”,它是数字,但如果转换为 int,它会改变。
  • 您可以将其转换为 float 或 double ($value = (double) $value)。我想这并没有什么坏处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2010-12-31
相关资源
最近更新 更多