How to Get the Last Four Digits of a Credit Card Number with PHP
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.
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
Comments
// Let’s use a fake credit card # for this example
$cc = “1122558877669911″;
// Build a new CC denoting only last 4, leaving all else with X’s
$new_card = “XXXX-XXXX-XXXX-” . substr($cc,-4,4);
// In case we need just the last four, let’s set a variable
$last_four = substr($cc,-4,4);
echo $last_four;


This Code WORKS!!!!!Two lines is all it takes. If you using the credit card num in a database..
Takes Alot