简体   繁体   English

如何将字符串转换为整数,但将“ foo”与“ 0”区分开?

[英]How to convert string to integer, but distinguish “foo” from “0”?

I need to convert strings to intiger but with distinguish "foo" from "0" , because intval() php function converts non numeric values to 0 . 我需要将字符串转换为intiger,但要区分"foo""0" ,因为intval() php函数会将非数字值转换为0

With inputs: 有输入:

$a = "10"
$b = "foo"
$c = "0"
$d = "10.5"

I expecting after convertion: 我期望转换后:

$a == 10
$b == "foo" // or false or whatever that is not an integer
$c == 0
$d == 10.5

You could always use is_numeric() . 您可以始终使用is_numeric()

if (is_numeric($value)) {
    $integer = (int) $value; // Or use intval()
    $floatOrInteger = $value + 0; // Can also give a float, so watch it.
} else {
    echo "Value is not numeric!";
}

See the code in action here: https://3v4l.org/j4Utb 在此处查看运行中的代码: https//3v4l.org/j4Utb

EDIT 编辑

Look at the comments of the documentation I linked if you want more fine-grained control. 如果您想要更细粒度的控制,请查看我链接的文档的评论。 There's tons of really useful tricks there. 那里有很多真正有用的技巧。

You could consider using conditional operator, code would like somehow as below: 您可以考虑使用条件运算符,代码可能会如下所示:

$foo = is_numeric($bar) ? (float) $bar : $bar;

There's no reason to overthink that solution, this should be enough. 没有理由去考虑该解决方案,这应该足够了。

You could use is_int to test, if it is really an integer. 如果确实是整数,则可以使用is_int进行测试。 After that, you have to determine, if it's a float. 之后,您必须确定它是否为浮点数。 A simple check like (int) $value == (float) $value could be sufficient in your case. (int) $value == (float) $value这样的简单检查就足够了。

Wrapping things up in a function could look like this: 在函数中包装内容可能如下所示:

function toNumber($value) {
    if (is_numeric($value)) {
        if ((int)$value != (float)$value) {
            return (float) $value;
        }
        return (int) $value;
    }
    return $value;
}

The result of your examples (and some others) would be 您的示例(和其他示例)的结果将是

var_dump(toNumber('10')) . "\n";
var_dump(toNumber('foo')) . "\n";
var_dump(toNumber('0')) . "\n";
var_dump(toNumber(10.5)) . "\n";
var_dump(toNumber('-10')) . "\n";
var_dump(toNumber('')) . "\n";
var_dump(toNumber('10.0')) . "\n";

with

int(10)
string(3) "foo"
int(0)
float(10.5)
int(-10)
string(0) ""
int(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM