422
422

Reputation: 5770

split integer into array ( each with a var )

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.

Upvotes: 0

Views: 295

Answers (3)

lePunk
lePunk

Reputation: 523

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>");
}

Upvotes: 0

Mr.Web
Mr.Web

Reputation: 7144

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.

Upvotes: 1

Nadh
Nadh

Reputation: 7243

<?php

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

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

?>

Upvotes: 1

Related Questions