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.

Download  Run Code

 
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.

Download  Run Code

 
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.

Download  Run Code

That’s all about converting the comma-delimited string to an array of ints in PHP.