[php] Convert array values from string to int?

The following code:

$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);

Returns the array:

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 foreach and converting each string to int?

This question is related to php arrays string integer explode

The answer is


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.

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.


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

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.


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

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

<?php
    
$string = "1,2,3";
$ids = explode(',', $string );

array_walk( $ids, function ( &$id )
{
    $id = (int) $id;
});
var_dump( $ids );

Another technique is to type-hint (coerce) the incoming values to int type after exploding the string.

Note that these techniques will work as demonstrated in my demo link unless you have set php to use strict typing.

The following techniques should not be used to sanitize non-numeric strings; it assumes that all values will be numeric.

If float values are passed into these techniques, they will be truncated/floored to integers.

Code: (Demo)

$string = "1,2,3";
$array = explode(',', $string);
var_dump($array);

echo "\n---\n";
array_walk($array, function(int &$int){;});
var_dump($array);

echo "\n---\n";
var_dump(
    array_map(function(int $i){ return $i; }, explode(',', $string))
);

echo "\n---\n";
var_dump(
    array_map(fn(int $i) => $i, explode(',', $string)) // PHP 7.4 arrow function syntax
);

Output:

array(3) {
  [0]=> string(1) "1"
  [1]=> string(1) "2"
  [2]=> string(1) "3"
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

Not sure if this is faster but flipping an array twice will cast numeric strings to integers:

$string = "1,2,3,bla";
$ids = array_flip(array_flip(explode(',', $string)));
var_dump($ids);

Important: Do not use this if you are dealing with duplicate values!


If you have a multi-dimensional 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.

Alternatively, you can use array_walk_recursive() for a shorter answer:

array_walk_recursive($array, function(&$value){
    $value = intval($value);
});

Input => '["3","6","16","120"]'

Type conversion I used => (int)$s;

function Str_Int_Arr($data){
    $h=[];
    $arr=substr($data,1,-1);
    //$exp=str_replace( ",","", $arr);
    $exp=str_replace( "\"","", $arr);
    $s=''; 
    $m=0;
    foreach (str_split($exp) as $k){
        if('0'<= $k && '9'>$k || $k =","){
            if('0' <= $k && '9' > $k){
                $s.=$k;
                $h[$m]=(int)$s;
            }else{
                $s="";
                $m+=1;
            } 
        } 
    } 
    return $h;
}
var_dump(Str_Int_Arr('["3","6","16","120"]'));

Output:

array(4) {
  [0]=>
  int(3)
  [1]=>
  int(6)
  [2]=>
  int(16)
  [3]=>
  int(120)
}

Thanks


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

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

An alternative shorter method could be:

$r = explode(',', $s);
foreach ($r as &$i) $i = (int) $i;

It has the same performance as Method 3.


PHP 7.4 style:

$ids = array_map(fn(string $x): int => (int) $x, explode(',', $string));

My solution is casting each value with the help of callback function:

$ids = array_map( function($value) { return (int)$value; }, $ids )

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to explode

How do I hide the PHP explode delimiter from submitted form results? Mysql where id is in array Convert array values from string to int? Php multiple delimiters in explode PHP: Split string into array, like explode with no delimiter Explode string by one or more spaces or tabs