Convert array values from string to int?
You can achieve this by following code,
$integerIDs = array_map('intval', explode(',', $string));
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.
$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:
$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.
$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.
Edit: It's been a while since the answer was originally posted. To clarify, the benchmark was done in php 5.6.40.
This is almost 3 times faster than explode()
, array_map()
and intval()
:
$integerIDs = json_decode('[' . $string . ']', true);
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:
// 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)
}
In Mark's solution, you will return array([0]=> int 0)
if you try to parse a string such as "test".
$integerIDs = array_map( 'intval', array_filter( explode(',', $string), 'is_numeric' ) );