Today, I had a friend ask me how to get the last four digits of a credit card number using PHP. I have done this at least a hundred times over the years and never really given it a second thought but for those new to PHP this could be a confusing task. It isn’t every day you need to divide up a string in this fashion.

Here is the way I use PHP to extract the last four digits of a credit card number. The beauty of this simple method is that it works both with and without the dashes in the credit card string.

<?PHP
    //CREDIT CARD… YES IT IS FAKE I AM NOT A TOOL
    $card =4121839020308678;
 
    //BUILD NEW STRING WITH LAST 4 DIGITS XXXX-XXXX-XXXX-8678
    $new_card = "XXXX-XXXX-XXXX-" . substr($card,-4,4);
?>

The function we are using is substr(). It can be used to create new strings by extracting portions of an existing string. In this case, we’re taking the last 4 characters of the string to create the credit card value.

I hope this helps, if you have questions leave a comment.