How to convert an integer to an array in PHP?

前端 未结 4 406
小鲜肉
小鲜肉 2020-12-03 17:43

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条回答
  • 2020-12-03 18:04

    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);
    
    0 讨论(0)
  • 2020-12-03 18:09

    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

    0 讨论(0)
  • 2020-12-03 18:20

    use str_split() function

    $array = str_split($str);
    

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

    0 讨论(0)
  • 2020-12-03 18:27

    Example #2 Splitting a string into component characters

    $str = 'string';
    $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
    
    0 讨论(0)
提交回复
热议问题