China (mainland) Citizen ID number each representative of the meaning of the Internet, many articles are introduced, this is not much to say. The last one of the ID card number is the check code, according to the first 17 digits calculated. The algorithm is probably this: the first 17 digits of each number and a series of weighted factors, and then calculate the sum of these products, the sum of these products and modulo 11 as the number of numbers, and finally in a check code string to extract the corresponding sequence of characters. Of course, there are many articles on the internet to teach you to calculate this check code, we will try to use the PHP language to complete this work, may be used in PHP development, such as verifying the user's identity card number is correct.
Suppose a Chinese (mainland) Citizen's ID number 17 is this: 44010221990101001 (note: This person was born in 2199), then we follow the above algorithm to try to write a few lines of PHP code to complete the checkout code calculation. To make it easier for everyone to understand, I used a simpler statement, see the code:
<?php
//ID number before 17, can be obtained from various data sources (such as database, user submitted form, etc.)
$body = ' 44010221990101001 ';
Weighted factor
$wi = Array (7, 9, 5, 8, 4, 2, 1, 6, 3, 7, 9, ten, 5, 8, 4, 2);
Check code string
$ai = Array (' 1 ', ' 0 ', ' X ', ' 9 ', ' 8 ', ' 7 ', ' 6 ', ' 5 ', ' 4 ', ' 3 ', ' 2 ');
Sequentially iterates through the first 17
for ($i = 0; $i < $i + +) {
//extract one of the first 17 digits and convert the variable type to the real
$b = (int) $body {$i};
Extracting the corresponding weighting factor
$w = $wi [$i];
Multiplies a number and weighted factor extracted from the ID card number and adds
$sigma + + $b * $w;
}
The number
$number = $sigma%;
Extracts the corresponding characters from the checksum code string by serial number.
$check _number = $ai [$number];
Output
echo $body. $check _number;
? >
After running the above code, you can figure out that the verification code for the ID card is 9. You can try the top 17 of your ID card.
If you understand the above example, you can combine some of the statements in this code, remove unnecessary variables, and optimize the following code:
<?php
$body = ' 44010221990101001 ';
$wi = Array (7, 9, 5, 8, 4, 2, 1, 6, 3, 7, 9, 5, 8, 4, 2);
$ai = Array (' 1 ', ' 0 ', ' X ', ' 9 ', ' 8 ', ' 7 ', ' 6 ', ' 5 ', ' 4 ', ' 3 ', ' 2 ');
for ($i = 0; $i < $i + +) {
$sigma + + (int) $body {$i}) * $wi [$i];
}
echo $body. $ai [($sigma%)];
>
The above is a small set to introduce the PHP ID check code calculation method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!