Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer to an array in PHP?

Tags:

arrays

php

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).

like image 879
rob.s Avatar asked Nov 14 '11 08:11

rob.s


People also ask

What does array () do in PHP?

An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index.

How do I convert an integer to a string in PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.


2 Answers

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

like image 95
Berry Langerak Avatar answered Sep 18 '22 12:09

Berry Langerak


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);
like image 39
4DA Avatar answered Sep 19 '22 12:09

4DA