-1

I need to be able to take in an integer and break it down to an array as shown below. However, explode doesn't work on integers, so I am trying to convert the int to a string, but that won't work as well for some reason. Any idea why this is and how to accomplish this?

$num = 321;
$numArr = explode(',',(string)$num);
var_dump($numArr);

Need it to return

array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "1"
}
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • I am limited to 5 dupes in the closure, but there are many more: https://stackoverflow.com/q/43290575/2943403 , https://stackoverflow.com/q/26922121/2943403 and plenty more – mickmackusa Nov 23 '19 at 14:27

2 Answers2

0

Simply use the string split function and reverse it.

$num = 321;
$array = str_split(strrev($num));
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • It is time to concentrate on closing new duplicates and repairing old content which is incorrect. There is plenty of bad advice in old pages. Please help this site in this meaningful way. When a new basic question is asked, close it with a dupe, then review the dupe page fully. If you can add a new insight, post on the old page, not the new page. SO is super bloated with redundant content. – mickmackusa Nov 23 '19 at 14:29
-1

Since your string is like $num = 321; in this case, 321 is only one word. Implode function works based on a string. And there is no comma between this word. So this is only one word. In that case (,) commas can't identify in your string. As a result, you're getting 321 in your zero (0) index.

You'll get the your desired output if the input value is looks like below:

$num = '3,2,1';
$numArr = explode(',',$num);
print_r($numArr);

Array ( [0] => 3 [1] => 2 [2] => 1 )

Md. Abutaleb
  • 1,590
  • 1
  • 14
  • 24