开发者

how can I get digits from the two digits?

I want to get the single digits from two digi开发者_如何学Cts.for example if 36 I need to store 3 and 6 in different variables.Is it possible?


You solve this with simple Mathematics.

First of all, think about what 36 really is, if you break it down, its 3 * 10 + 6, right?

So the first digit in this case represents your times 10, which you will get by dividing by 10:

36 / 10 = 3.xxxxx

Now if you round that you get 3, which is the first digit.

How about the rest of that? Well, for that you have to use something called modulo, which can be hard to understand some times. But it baslicy takes out the left overs of a integer division.

IT bascily means that when you do 36 % 10 you get 6. Why is that you might think? Try open a calculator and push in the numbers: 36 / 10 = 3.6, the left overs are 6!

Solution Code

<?php
    $theNumber = 36;

    $first = floor($theNumber / 10);

    $second = $theNumber % 10;    
?>

You can look into the function floor here.

Alternative Solution for splitting strings

If you are looking for alternative ways to split strings in PHP you can use str_split, this will provide you with an array of characters.

Example

<?php
    $myString = "36 is my number";

    $splittedString = str_split($myString);

    echo $splittedString[0];
    echo $splittedString[1];
?>

Just use that one as an array


basically

"string" way

$s = (string) $i;
$one = $s[0];
$two = $s[1];

"math" way

$two = $i % 10;
$one = ($i - $two) / 10;


This way:

$int = 36;
$str = (string)$int;
var_dump($str[0], $str[1]);


A string can be accessed as an array. If you convert your number to a string (or if it already is one - you don't mention), you can address the digits individually and then optionally convert them back to integers:

$num = strval(36);

echo intval($num[0]); // 3
echo intval($num[1]); // 6


One of the ways:

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f


This is not PHP code!! (Didn't see the tag)

int num = 36;
int first = num / 10; // 3
int second = num % 10; // 6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜