bandanh
bandanh

Reputation: 555

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

And the I run out of ideas :-/

I'm on PHP 7.1.19 (cli)

Upvotes: 3

Views: 188

Answers (7)

Akshay Bande
Akshay Bande

Reputation: 2587

You can use this

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

Upvotes: 0

ggorlen
ggorlen

Reputation: 57155

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

Upvotes: 0

NAD
NAD

Reputation: 46

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

Upvotes: 2

napuzba
napuzba

Reputation: 6298

Match the string by regular expression of int format:

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

Upvotes: 1

Goms
Goms

Reputation: 2644

Try this

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

Upvotes: 0

cherrysoft
cherrysoft

Reputation: 1195

You can do as follows...

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

Upvotes: 1

manu
manu

Reputation: 351

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

Upvotes: 2

Related Questions