0

I saw this particular question asked here

My issue is slightly different.

Lets say I have a random integer ( could be any number )

Like so: $rank=123456

Equally it could be $rank=2876545672

What I want to do is split the integer into an array dynamically, and give each value a class.

so it would grab in the example: 123456 the first number and give assign a var like digit-<?=$num['id']

So I could then generate something like:

<span class="digit-1">1</span>
<span class="digit-2">2</span>
<span class="digit-3">3</span>
<span class="digit-4">4</span>
<span class="digit-5">5</span>
<span class="digit-6">6</span>

Is this possible, and if so any ideas how to achieve this ? As tha bove ( spans ) would need to act dynamically so that they are created based on whatever number was generated.

Driving me nuts trying to figure it out.

Community
  • 1
  • 1
422
  • 5,714
  • 23
  • 83
  • 139
  • 1
    Use [`str_split`](http://php.net/manual/en/function.str-split.php). `$vals = str_split($rank);` :-) – gen_Eric Jul 05 '13 at 16:23
  • see this question http://stackoverflow.com/questions/4868896/how-do-i-explode-an-integer and apply your html boilerplate around – mnagel Jul 05 '13 at 16:24

3 Answers3

1
<?php

    $rank = 123456;
    $numbers = str_split($rank."");

    foreach($numbers as $n) {
        echo '<span class="digit-'.$n.'">'.$n.'</span>'."\n";
    }

?>
Nadh
  • 6,987
  • 2
  • 21
  • 21
1

Try this out:

<?php

$rank = 123456;
$div = str_split($rank);

foreach ($div as $key) {
    echo '<span class="digit-', $key, '">', $key, '</span>';
} 

?>

I used commas instead of dots as the code loads faster.

Mr.Web
  • 6,992
  • 8
  • 51
  • 86
0

not sure I understand you correctly but:

$test = 12345;
$test = (string) $test;
for($i = 0; $i < strlen($test); $i++){
    print("<span class=\"digit-{$test[$i]}\">{$test[$i]}</span>");
}
lePunk
  • 523
  • 3
  • 10