Convert a Comma-Delimited String into an Array of Integers
In a recent coding scenario, a developer was tasked with converting a string of comma-separated integers into an array of integers. The provided code:
<pre class="brush:php;toolbar:false">$string = "1,2,3" $ids = explode(',', $string); var_dump($ids);
resulted in an array of strings, rather than integers. To address this issue, the developer posed the following question:
Concern:
I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with foreach and converting each string to int?
Solution:
To achieve the desired conversion, a more efficient approach is to use the array_map() function along with explode(). The corrected code:
<pre class="brush:php;toolbar:false">$integerIDs = array_map('intval', explode(',', $string));
Now, the result of var_dump($integerIDs) will yield:
<pre class="brush:php;toolbar:false">array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
This solution eliminates the need for manual looping and provides a more concise method for converting the comma-delimited string into an array of integers.
The above is the detailed content of How to Efficiently Convert a Comma-Separated String of Integers into an Integer Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!