Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

convert string array to array of int(s)

Hello ,

How to convert this string

'["382","266","18","60"]'

to int array

[382,266,18,60]

Thanks

1 like
9 replies
Braunson's avatar

array_map to intval ;-)

$array = ["123", "34", "223"];
$integerIDs = array_map('intval', $array);
5 likes
GodziLaravel's avatar

thanks ,

but ' ["123", "34", "223"]' is not array by default , it's a string !

wafto's avatar

Continue the code from Brauson only use json_decode first in your string.

$integerIDs = array_map('intval', json_decode($string, true));
2 likes
Snapey's avatar

just json_decode should do it?

2 likes
mstrauss's avatar

@snapey is right, json_decode('["382","266","18","60"]') seems like the cleanest way to do it. No need for a mapping or the associative argument.

wafto's avatar

It necessary when he really wants an array of integers, if he don´t use it it will only be an array of strings even that the value seems to be an integer.

1 like
mstrauss's avatar

Good call @wafto . I just double checked and you're 100% right, see below:

array_map('intval', json_decode('["382","266","18","60"]'));

Output:

array:4 [▼
  0 => 382
  1 => 266
  2 => 18
  3 => 60
]

Whereas:

json_decode('["382","266","18","60"]')

Output (strings):

array:4 [▼
  0 => "382"
  1 => "266"
  2 => "18"
  3 => "60"
]
1 like

Please or to participate in this conversation.