19

What would be the most simple way to convert an integer to an array of numbers?

Example:

2468 should result in array(2,4,6,8).

4 Answers 4

55

You can use str_split and intval:

$number = 2468;

    $array  = array_map('intval', str_split($number));

var_dump($array);

Which will give the following output:

array(4) {
  [0] => int(2)
  [1] => int(4)
  [2] => int(6)
  [3] => int(8)
}

Demo

2
  • Ya. Just convert the int value to a string and split it. Nov 14, 2011 at 8:41
  • str_split does convert to string already. However the output wasn't an array of integers,, so this needed actually some conversion.
    – hakre
    Oct 21, 2012 at 14:21
8

use str_split() function

$array = str_split($str);

http://php.net/manual/en/function.str-split.php

7

You can cut-off the last digit by taking the number modulo 10.

Don't tell it to anyone!

do 
{
    $array.add(num % 10);
    num = num / 10;
}
while (num != 0);
1
  • 4
    Wait, wha...? Don't tell it to anyone? Why?
    – Cullub
    Jan 28, 2016 at 21:32
0

Example #2 Splitting a string into component characters

$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
1
  • 2
    str_split() from the other answeres would perform much better (i'll guess).
    – breiti
    Nov 14, 2011 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.