Sanks Raut
Sanks Raut

Reputation: 31

How to split the digit in php

How can I achieve number 4,7,8 separately if there is a given variable: $i=478 such that I can store $j=4,$k=7,$l=8 in PHP. Is there a function?

Upvotes: 3

Views: 21580

Answers (4)

xkeshav
xkeshav

Reputation: 54022

try

 $n=567;
 $x = (string)$n;
 for($i=0;$i<strlen($x);$i++)
 { 
    echo "<br/>".$x[$i];
 }

UPDATE:

to find the average

for($i=0;$i<strlen($x);$i++)
     { 
        echo "<br/>".$x{$i};
        $t+=(int)$x[$i];
     }
echo  "average:". $t/strlen($x);

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86386

Use type case and convert number to string

$i=478 ;
$i= (string)$i ;

String can be accessed as array hence you can do

echo $i[0]; //to access 4

you can iterate as array as well using loops

$len=strlen($i);
for($j=0; $j <= $len; $j++)
{
   echo $i[$j]."<br>";
}

Upvotes: 2

Rudie
Rudie

Reputation: 53821

You should cast the number to a string and then str_split it:

$numbers = str_split((string)$number); // or
list($a, $b, $c) = str_split((string)$number); // but this might throw a notice if $number is 12 or 8 or something

Upvotes: 5

MeLight
MeLight

Reputation: 5565

$i = 478;
$stri = (string)$i;
$j = $stri[0];
$k = $stri[1];
$l = $stri[2];

Upvotes: 7

Related Questions