3

so tonight i was trying to create a function that will check if a credit card is valid or not. However i'm stuck here. In my calcul, i get number such as 10, 56, 30... number with 2 numbers.

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

What I need to do is :

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

Example:

I have this number -> 23

I need to :

$var1 = 2;

$var2 = 3;

I wanted to use the function subtr, but it looks like it doesn't works with numbers ..

Thanks for reading !!

newQuery
  • 78
  • 1
  • 9
  • i don't understand your approach but the proper way to do it is ^^^^^^^ –  Apr 21 '15 at 02:56

4 Answers4

1

I hope you get something from this. Casting the number into a string first and then split the number using substr() after that cast the splitted value to integer again:

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

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

Or using a pure numbers:

$num = 23;

$var2 = $num % 10;
$var1 = ($num - $var2) / 10;
Ceeee
  • 1,392
  • 2
  • 15
  • 32
0

Credit card numbers can be validated using an algorithm called the Luhn Algorithm.

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

Drew Hammond
  • 588
  • 5
  • 19
0

Here's a way to do this using purely numbers (without ever casting to strings). This'll also work on any length of numbers assigning it to $var1, $var2, ... , $varn for n length number.

$num = 23;
$count = 1;
while ($num > 0) {
    $var = "var".$count++;
    $$var = $num % 10;
    $num = intval($num / 10);
}
MasterOdin
  • 7,117
  • 1
  • 20
  • 35
0

a numeric solution

$num = 23;
$var1 = floor($num / 10);
$var2 = $num % 10;
echo "$var1 $var2";
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62