php 如何将数组值从字符串转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9593765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert array values from string to int?
提问by cwal
$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);
returns
返回
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with a foreach and converting each string to int?
我需要这些值是 int 类型而不是 string 类型。有没有比用 foreach 循环遍历数组并将每个字符串转换为 int 更好的方法?
回答by Mark Baker
You can achieve this by following code,
您可以通过以下代码实现这一点,
$integerIDs = array_map('intval', explode(',', $string));
回答by sgrodzicki
This is almost 3 times faster than explode()
, array_map()
and intval()
:
这几乎比 快 3 倍explode()
,array_map()
并且intval()
:
$integerIDs = json_decode('[' . $string . ']', true);
回答by MikeWu
So I was curious about the performance of some of the methods mentioned in the answers for large number of integers.
所以我对大量整数的答案中提到的一些方法的性能感到好奇。
Preparation
准备
Just creating an array of 1 million random integers between 0 and 100. Than, I imploded them to get the string.
只需创建一个包含 0 到 100 之间的 100 万个随机整数的数组。然后,我将它们内爆以获取字符串。
$integers = array();
for ($i = 0; $i < 1000000; $i++) {
$integers[] = rand(0, 100);
}
$long_string = implode(',', $integers);
Method 1
方法一
This is the one liner from Mark's answer:
这是马克的回答中的一个班轮:
$integerIDs = array_map('intval', explode(',', $long_string));
Method 2
方法二
This is the JSON approach:
这是 JSON 方法:
$integerIDs = json_decode('[' . $long_string . ']', true);
Method 3
方法三
I came up with this one as modification of Mark's answer. This is still using explode()
function, but instead of calling array_map()
I'm using regular foreach
loop to do the work to avoid the overhead array_map()
might have. I am also parsing with (int)
vs intval()
, but I tried both, and there is not much difference in terms of performance.
我想出了这个作为对马克答案的修改。这仍在使用explode()
函数,但array_map()
我没有调用,而是使用常规foreach
循环来完成工作以避免array_map()
可能产生的开销。我也在用(int)
vs解析intval()
,但是我两个都试过,性能上没有太大区别。
$result_array = array();
$strings_array = explode(',', $long_string);
foreach ($strings_array as $each_number) {
$result_array[] = (int) $each_number;
}
Results:
结果:
Method 1 Method 2 Method 3
0.4804770947 0.3608930111 0.3387751579
0.4748001099 0.363986969 0.3762528896
0.4625790119 0.3645150661 0.3335959911
0.5065748692 0.3570590019 0.3365750313
0.4803431034 0.4135499001 0.3330330849
0.4510772228 0.4421861172 0.341176033
0.503674984 0.3612480164 0.3561749458
0.5598649979 0.352314949 0.3766179085
0.4573421478 0.3527538776 0.3473439217
0.4863037268 0.3742785454 0.3488383293
The bottom line is the average. It looks like the first method was a little slower for 1 million integers, but I didn't notice 3x performance gain of Method 2 as stated in the answer. It turned out foreach
loop was the quickest one in my case. I've done the benchmarking with Xdebug.
底线是平均值。看起来第一种方法对于 100 万个整数来说有点慢,但我没有注意到答案中提到的方法 2 的 3 倍性能提升。结果证明foreach
在我的情况下循环是最快的。我已经用 Xdebug 完成了基准测试。
Edit: It's been a while since the answer was originally posted. To clarify, the benchmark was done in php 5.6.
编辑:自从最初发布答案以来已经有一段时间了。澄清一下,基准测试是在 php 5.6 中完成的。
回答by Andreas
Use this code with a closure (introduced in PHP 5.3
), it's a bit faster than the accepted answer and for me, the intention to cast it to an integer, is clearer:
将此代码与闭包(在 中引入PHP 5.3
)一起使用,它比接受的答案要快一点,对我来说,将其转换为整数的意图更清晰:
// if you have your values in the format '1,2,3,4', use this before:
// $stringArray = explode(',', '1,2,3,4');
$stringArray = ['1', '2', '3', '4'];
$intArray = array_map(
function($value) { return (int)$value; },
$stringArray
);
var_dump($intArray);
Output will be:
输出将是:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
回答by Dmitry Dubovitsky
In Mark's solution, you will return array([0]=> int 0)
if you try to parse a string such as "test".
在 Mark 的解决方案中,array([0]=> int 0)
如果您尝试解析诸如“test”之类的字符串,您将返回。
$integerIDs = array_map( 'intval', array_filter( explode(',', $string), 'is_numeric' ) );
回答by baikho
Not sure if this is faster but flipping the array twice will cast numeric strings to integers:
不确定这是否更快,但翻转数组两次会将数字字符串转换为整数:
$string = "1,2,3, bla";
$ids = array_flip(array_flip(explode(',', $string)));
var_dump($ids);
回答by MyGeertRo
An alternative shorter method could be:
另一种更短的方法可能是:
$r = explode(',', $s);
foreach ($r as &$i) $i = (int) $i;
It has the same performance as Method 3.
它具有与方法3相同的性能。
回答by star18bit
If you have array like:
如果你有这样的数组:
$runners = ["1","2","3","4"];
And if you want to covert them into integers and keep within array, following should do the job:
如果您想将它们转换为整数并保留在数组中,则应执行以下操作:
$newArray = array_map( create_function('$value', 'return (int)$value;'),
$runners);
回答by Theva
My solution is casting each value with the help of callback function:
我的解决方案是在回调函数的帮助下投射每个值:
$ids = array_map( function($value) { return (int)$value; }, $ids )
回答by Devashish Jaiswal
Keep it simple...
把事情简单化...
$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);
Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode ()
. People have posted how to use that, so I am not including it here.
你为什么要寻找其他方式?循环可以轻松完成工作。如果您关心性能,则可以使用json_decode ()
. 人们已经发布了如何使用它,所以我不包括在这里。
Note:When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:
注意:当使用 == 运算符而不是 === 时,如果您的字符串值形成不带引号的有效数字,则它们会自动转换为数字(例如整数或双精度数)。例如:
$str = '1';
($str == 1) // true but
($str === 1) //false
Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.
因此, == 可以解决您的问题,效率很高,但如果您在比较中使用 === 则会中断。