Convert Strings that hold only an Number into INT

I got an array full of items, all are strings. 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)

Answer

Try i’s_numeric’ It will find whether a variable is a number or a numeric string http://php.net/manual/en/function.is-numeric.php