Converting positive integers to an array of digits is fairly straightforward. However, the complication arises with negative integers, specifically in how you add the negative sign (-
) to the resulting array. For example, following are a few options:
- Make the Most Significant Digit Negative;
- Add the Minus Sign as a String;
- Add a Leading Digit to Represent the Sign.
Make the Most Significant Digit Negative
Making the most significant digit negative means that in the resulting array, if the original number is negative, the first digit will have the negative sign:
// -12345 becomes [-1, 2, 3, 4, 5]
To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:
- Convert number (or numeric string) to an array of numeric string digits using
preg_match_all()
with a regular expression ; - Use
array_map()
to convert each array item to an integer, (by passingintval
and array of matches as an argument to it).
function numToArray(int $num): array { $matches = []; // 1: use regex to match '-' (optionally) and numbers preg_match_all('/-?\d/', $num, $matches); // 2: convert each item to an integer return array_map('intval', $matches[0]); } var_dump(numToArray(12345)); // [1, 2, 3, 4, 5] var_dump(numToArray(-12345)); // [-1, 2, 3, 4, 5] var_dump(numToArray('12345')); // [1, 2, 3, 4, 5] var_dump(numToArray('-12345')); // [-1, 2, 3, 4, 5]
It is safe to directly access $matches[0]
in this case because the int
typehint added to the function argument ensures $num
is always an integer, which means that the regular expression is guaranteed to have at least one match and preg_match_all()
will always return an array of arrays. When an argument of some other type is passed in, a TypeError
will be thrown.
Add the Minus Sign as a String
Adding the minus sign (-
) as a string means that in the resulting array, if the original number is negative, the first element of the array will have the minus sign as a string:
// -12345 becomes ['-', 1, 2, 3, 4, 5]
To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:
- Convert string to an array of numeric string characters using
str_split()
; - Use
array_map()
to go over each array item and cast toint
(except if minus sign is found, in which case, it is added as is).
// PHP 7.4+ function numToArray(int $num): array { // 1: convert number (or numeric string) to array of numeric string digits $numericArr = str_split($num); // 2: convert each array item to an integer (and add '-' as is if present) return array_map(fn ($currNum) => ( ($currNum === '-') ? '-' : (int) $currNum ), $numericArr); } var_dump(numToArray(12345)); // [1, 2, 3, 4, 5] var_dump(numToArray(-12345)); // ['-', 1, 2, 3, 4, 5] var_dump(numToArray('12345')); // [1, 2, 3, 4, 5] var_dump(numToArray('-12345')); // ['-', 1, 2, 3, 4, 5]
If you're using a version of PHP prior to 7.4, then you can use a regular function instead of the arrow function syntax.
Add a Leading Digit to Represent the Sign
Adding a leading digit to represent the sign means that in the resulting array, the first element can be used to represent the sign (i.e. 0
for positive integers and 1
for negative integers):
// 12345 becomes [0, 1, 2, 3, 4, 5] // -12345 becomes [1, 1, 2, 3, 4, 5]
To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:
- Convert the integer to a string;
- Check if the first element of array is the negative sign and cast the resulting boolean value to number, which would result in
1
if the negative sign is present and0
otherwise; - Add the leading digit for the sign (i.e.
0
or1
) as the first element of the new array; - Loop over each character in the string, converting each one to an integer, and adding it to the new array one by one.
function numToArray(int $num): array { // 1: convert number to string $numericStr = (string) $num; // 2: determine leading digit (i.e. 0 for positive, and 1 for negative) $leadingDigit = (int) ($numericStr[0] === '-'); // 3: add leading digit (for sign) to new array $numbersArr = [$leadingDigit]; $totalDigits = strlen($numericStr); // 4: iterate over string chars, convert to an integer and add to array for ($i = $leadingDigit; $i < $totalDigits; $i++) { $numbersArr[] = (int) $numericStr[$i]; } return $numbersArr; } var_dump(numToArray(12345)); // [0, 1, 2, 3, 4, 5] var_dump(numToArray(-12345)); // [1, 1, 2, 3, 4, 5] var_dump(numToArray('12345')); // [0, 1, 2, 3, 4, 5] var_dump(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
It is safe to directly access $numericStr[0]
in this case because the int
typehint added to the function argument ensures $num
is always an integer, which means that the integer is guaranteed to have at least one digit. When an argument of some other type is passed in, a TypeError
will be thrown.
As an alternative, you can achieve the same result in the following way as well:
- Convert string to an array of numeric string characters using
str_split()
; - Check, remove and remember, if the first element of array is the negative sign;
- Convert each array item to an integer by passing
intval
and the numeric array as an argument toarray_map()
; - Use
array_unshift()
to add the leading digit for the sign to the front of the array.
function numToArray(int $num): array { // 1: convert number (or numeric string) to array of numeric string digits $numericArr = str_split($num); // 2: is first element minus sign? $hasSign = ($numericArr[0] === '-'); if ($hasSign) { // remove minus sign from array array_shift($numericArr); } // 3: convert each array item to an integer $intArr = array_map('intval', $numericArr); // 4: add 0 or 1 as first element in array array_unshift($intArr, (int) $hasSign); return $intArr; } var_dump(numToArray(12345)); // [0, 1, 2, 3, 4, 5] var_dump(numToArray(-12345)); // [1, 1, 2, 3, 4, 5] var_dump(numToArray('12345')); // [0, 1, 2, 3, 4, 5] var_dump(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
It is safe to directly access $numericArr[0]
array index in this case because the int
typehint added to the function argument ensures $num
is always an integer, which means str_split()
is guaranteed to return an array with at least one element. When an argument of some other type is passed in, a TypeError
will be thrown.
Another way of achieving the same result would be to follow these steps:
- Check, and remember, if the numeric string starts with the negative sign;
- Convert number (or numeric string) to an array of numeric string digits using
preg_match_all()
with a regular expression; - Use
array_map()
to convert each array item to an integer, (by passingintval
and array of matches as an argument to it).
function numToArray(int $num): array { // 1: number (or numeric string) starts with minus sign? $hasSign = str_starts_with($num, '-'); $matches = []; // 2: use regex to match only numbers preg_match_all('/\d/', $num, $matches); // 3: add leading digit for sign to (converted) array of digits return [(int) $hasSign, ...array_map('intval', $matches[0])]; } var_dump(numToArray(12345)); // [0, 1, 2, 3, 4, 5] var_dump(numToArray(-12345)); // [1, 1, 2, 3, 4, 5] var_dump(numToArray('12345')); // [0, 1, 2, 3, 4, 5] var_dump(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
It is safe to directly access $matches[0]
in this case because the int
typehint added to the function argument ensures $num
is always an integer, which means that the regular expression is guaranteed to have at least one match and preg_match_all()
will always return an array of arrays. When an argument of some other type is passed in, a TypeError
will be thrown.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.