Convert a comma-delimited string to an int array in PHP
This article demonstrates how to convert a comma-delimited string to an array of ints in PHP.
1. Using array_map() function
The array_map() function is used to apply a callback function to each element of an array. You can use it to convert the comma-delimited numeric values from a string to an array of integers. The idea is to split the string with explode() using a comma as the delimiter. The explode() function returns an array of strings, which can then be passed to array_map() with intval() as a callback.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $string = '1,2,3,4,5'; $nums = array_map('intval', explode(',', $string)); print_r($nums); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
Note that the intval() function returns the integer value of the specified scalar type. If your string contains decimal values, you can use the floatval() function as a callback, which gets the float value of a variable.
2. Using json_decode() function
The json_decode() function takes an JSON encoded string and converts it into an appropriate PHP type. You can use it as follows to convert a comma-delimited numeric string to an array of integers: The idea is to invoke json_decode() with the second parameter set to true, which returns the JSON objects as associative arrays.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $string = '1,2,3,4,5'; $nums = json_decode("[$string]", true); print_r($nums); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
Alternatively, you can set the JSON_OBJECT_AS_ARRAY flag, which decodes the JSON objects as PHP arrays. Although, PHP automatically adds this option when the second parameter is true, the flag improves the readability of code.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $string = '1,2,3,4,5'; $nums = json_decode("[$string]", flags: JSON_OBJECT_AS_ARRAY); print_r($nums); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
That’s all about converting the comma-delimited string to an array of ints in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)