Search code examples
phpvariablessplitintegerdigits

Declare 1st and 2nd digit of a 2-digit number as separate variables


I have this code

$num = 53;

$num2 = sprintf("%02d", $num);//make sure $num is 2 digits 
$d1 = substr($num2, 1);//get first digit
$d2 = substr($num2, -1);//get second digit

d1 should be 5 and d2 should be 3 but both of them are 3. Can someone please tell me why?


Solution

  • Character index of a string begin with 0, so to get the first char you should use:

    substr($num2, 0, 1);
    

    or

    $num2[0];