0

I have a array like this:

array (size=3)
  'money' => string '16' (length=2)
  'str' => string '45' (length=2)
  'intl' => string '0' (length=1)

I want to convert string values to int like this:

array (size=3)
  'money' => int 16
  'str' => int 45
  'intl' => int 0

I tried to use foreach method:

$newuserattri=[];
foreach ($userattri as $key => $var) {
    $userattri[$key] = (int)$var;
    $newuserattri[]=$userattri[$key];
}
var_dump($newuserattri);

But that dident work, because now I dont have array value names

array (size=3)
  0 => int 16
  1 => int 45
  2 => int 0
Godhaze
  • 155
  • 3
  • 16

2 Answers2

3

You were actually close! You have to add them to the array with their original key like this:

$newuserattri = [];
foreach ($userattri as $key => $value) {
    $newuserattri[$key] = (int)$value;
}
var_dump($newuserattri);
Edwin
  • 1,135
  • 2
  • 16
  • 24
0

Replace

 $userattri[$key] = (int)$var;

With

$newuserattri[$key] = intval($var);
bsguy
  • 91
  • 4
  • This doesn't address the problem. The question shows that the array indexes have been converted to integers, and not that there is a problem with the value. The full solution would have `$newuserattri[$key]=$userattri[$key];` – Bob Dalgleish Sep 01 '17 at 15:10
  • My mistake. @BobDalgleish is correct. – bsguy Sep 01 '17 at 15:15
  • You can edit your answer to incorporate the feedback. You might mention the comment as reason for the edit, to keep it from looking unfounded. You might however want to add some explanation to the basically code-only answer. – Yunnosch Sep 01 '17 at 20:31