IT & Programming

Mask credit card number with X in PHP

Function accepts credit card number as string parameter and returns masked credit card number except last 4 digits.

Function

function maskCreditCard($cc) {

    $cc_length = strlen($cc);

    for ($i = 0; $i < $cc_length - 4; $i++) {
	
        if ($cc[$i] == '-') {
		
            continue;
        }
		
	$cc[$i] = 'X';
    }

    return $cc;
}

Calling The Function

$string = '8888-9999-6666-7777';

echo maskCreditCard($string);

Output

XXXX-XXXX-XXXX-7777

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *