如何将数组值从字符串转换为int?

时间:2022-09-25 08:06:51
$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更好的方法吗?

10 个解决方案

#1


386  

$integerIDs = array_map('intval', explode(',', $string));

#2


32  

This is almost 3 times faster than explode(), array_map() and intval():

这几乎比爆炸()、array_map()和intval()快3倍:

$integerIDs = json_decode('[' . $string . ']', true);

#3


24  

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.

我想出了这个修改马克的答案。这仍然使用了explosion()函数,但是我并没有调用array_map(),而是使用常规foreach循环来完成这项工作,以避免array_map()的开销。我也使用(int)和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倍性能提高,正如答案所示。结果证明,对于我来说,每一个环路都是最快的。我已经用Xdebug做了基准测试。

#4


13  

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)
}

#5


9  

$integerIDs = array_map( 'intval', array_filter( explode(',', $string), 'is_numeric' ) );

$integerIDs = array_map('intval'、array_filter(explosion('、'、$string)、'is_numeric'));

In Mark's solution, you will return array([0]=> int 0) if you try to parse a string such as "test".

在Mark的解决方案中,如果您试图解析一个字符串(如“test”),您将返回数组([0]=> int 0)。

#6


3  

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);

#7


3  

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);

#8


2  

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:

注意:当使用==操作符而不是===时,如果字符串值没有引号,则会自动转换成数字(例如整数或double)。例如:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

因此,=可以解决您的问题,是有效的,但是如果您在比较中使用=== =的话,就会中断。

#9


2  

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相同。

#10


1  

If you have a multi-dimentional array, none of the previously mentioned solutions will work. Here is my solution:

如果您有一个多维数组,前面提到的任何解决方案都不能工作。这是我的解决方案:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

然后,这样做:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

这将产生一个这样的数组:

[["1","2"]["3","4"]]

look like this:

看起来像这样:

[[1,2][3,4]

(This will work with any level of depth)

(任何深度都可以)

#1


386  

$integerIDs = array_map('intval', explode(',', $string));

#2


32  

This is almost 3 times faster than explode(), array_map() and intval():

这几乎比爆炸()、array_map()和intval()快3倍:

$integerIDs = json_decode('[' . $string . ']', true);

#3


24  

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.

我想出了这个修改马克的答案。这仍然使用了explosion()函数,但是我并没有调用array_map(),而是使用常规foreach循环来完成这项工作,以避免array_map()的开销。我也使用(int)和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倍性能提高,正如答案所示。结果证明,对于我来说,每一个环路都是最快的。我已经用Xdebug做了基准测试。

#4


13  

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)
}

#5


9  

$integerIDs = array_map( 'intval', array_filter( explode(',', $string), 'is_numeric' ) );

$integerIDs = array_map('intval'、array_filter(explosion('、'、$string)、'is_numeric'));

In Mark's solution, you will return array([0]=> int 0) if you try to parse a string such as "test".

在Mark的解决方案中,如果您试图解析一个字符串(如“test”),您将返回数组([0]=> int 0)。

#6


3  

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);

#7


3  

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);

#8


2  

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:

注意:当使用==操作符而不是===时,如果字符串值没有引号,则会自动转换成数字(例如整数或double)。例如:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

因此,=可以解决您的问题,是有效的,但是如果您在比较中使用=== =的话,就会中断。

#9


2  

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相同。

#10


1  

If you have a multi-dimentional array, none of the previously mentioned solutions will work. Here is my solution:

如果您有一个多维数组,前面提到的任何解决方案都不能工作。这是我的解决方案:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

然后,这样做:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

这将产生一个这样的数组:

[["1","2"]["3","4"]]

look like this:

看起来像这样:

[[1,2][3,4]

(This will work with any level of depth)

(任何深度都可以)