'Convert Strings that hold only an Number into INT

I got an array full of items, all are string. But many of the items should be INT.

I got:

$myArray = [
    'id' => '123',
    'title' => 'Hello World',
    'count' => '333'
];

I want:

$myArray = [
    'id' => 123,
    'title' => 'Hello World',
    'count' => 333
];

I tried:

foreach ($myArray as $key => $value) {
    if($value == (int)$value) {
        $myArray[$key] = (int)$value;
    }
}
  • $value == (int)$value is always true and kills my title
  • $value === (int)$value is always false my id and count are still string
  • is_int($value) is always false my id and count are still string

And the I run out of ideas :-/

I'm on PHP 7.1.19 (cli)



Solution 1:[1]

//If you want just integer, use this

$myArray = [
    'id' => '123',
    'title' => 'Hello World',
    'count' => '333'
];

foreach ($myArray as $key => $value) {
    if(IsIntegerOnly($value)) {
        $myArray[$key] = (int)$value;
    }
}


function IsIntegerOnly($str)
{
  return (is_numeric($str) && $str >= 0 && $str == round($str));
}

Solution 2:[2]

You can do as follows...

array_walk(&$array,
    create_function('&$value', '$value = (int)$value;');
);

Solution 3:[3]

Match the string by regular expression of int format:

foreach ($myArray as $key => $value) {
    if(preg_match('/^-?\d+$/', $value)) {
        $myArray[$key] = (int)$value;
    }
}

Solution 4:[4]

Try this

  foreach ($myArray as $key => $value) {
    if(preg_match('/^-?[0-9.]+$/', $value)) {
        $myArray[$key] = (int)$value;
    }
}

Solution 5:[5]

Checking numeric and then casting to int can cause accidental truncation of floats. Here's an option to handle such cases with regex:

$myArray = [
    'id' => '123',
    'title' => 'Hello World',
    'count' => '333.7',
    'something' => '-55.6',
    'something else' => '-.26'
];

foreach ($myArray as $k => $v) {
    if (preg_match('`^-?\d+$`', $v)) {
        $myArray[$k] = (int)$v;
    }
    else if (preg_match('`^-?\d*\.\d+`', $v)) {
        $myArray[$k] = (double)$v;
    }
}

var_dump($myArray);

Output

array(5) {
  ["id"]=>
  int(123)
  ["title"]=>
  string(11) "Hello World"
  ["count"]=>
  float(333.7)
  ["something"]=>
  float(-55.6)
  ["something else"]=>
  float(-0.26)
}

Solution 6:[6]

You can use this

foreach ($myArray as $key => $value) {
    if($key == 'id' || $key =='count') {
        $myArray[$key] = (int)$value;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NAD
Solution 2 cherrysoft
Solution 3
Solution 4 Goms
Solution 5
Solution 6 nito