Extract one number from another number in PHP

so today I was trying to create a function that checks if a credit card is valid or not. However, I am stuck here. In my calculation, I get a number like 10, 56, 30 ... a number with two numbers.

(I mean 1 is a number with 1 number, like 2, 3, 4, 5 6, 7, 8, 9 .. a number with two numbers will be 10 and higher).

What do I need to do:

  • Get the first number and add it to a new variable and do the same with another variable.

Example:

I have this number -> 23

I need:

$ var1 = 2;

$ var2 = 3;

I wanted to use the subtr function, but it doesn't seem to work with numbers.

Thanks for reading!

+3


source to share


4 answers


I hope you get something out of this. First enter the number into a string and then split the number using substr (), then split the value by an integer again:

$num = 23;
$str_num = (string)$num;

$var1 = (int)substr($str_num, 0, 1);
$var2 = (int)substr($str_num, 1, 1);

      



Or using pure numbers:

$num = 23;

$var2 = $num % 10;
$var1 = ($num - $var2) / 10;

      

+1


source


Credit card numbers can be verified using an algorithm called Luna's algorithm .



If you need it on a project, don't reinvent the wheel. Check out this project on github.

0


source


Here's a way to do it using pure numbers (no casting to strings). This will also work on any length of numbers by assigning $ var1, $ var2, ..., $ varn to it for n number of length.

$num = 23;
$count = 1;
while ($num > 0) {
    $var = "var".$count++;
    $$var = $num % 10;
    $num = intval($num / 10);
}

      

0


source


numerical solution

$num = 23;
$var1 = floor($num / 10);
$var2 = $num % 10;
echo "$var1 $var2";

      

0


source







All Articles