Home > Article > Backend Development > PHP ID card verification code calculation method_php example
The meaning of each Chinese (Mainland) citizen ID number is introduced in many articles on the Internet, so I won’t go into details here. The last digit of the ID number is the check code, which is calculated based on the first 17 digits. The algorithm is roughly like this: multiply each number in the first 17 digits by a series of weighting factors, and then calculate the sum of these products; use the sum of these products modulo 11 as the serial number, and finally extract it from a check code string Output the characters corresponding to the serial number. Of course, there are many articles on the Internet teaching you to calculate this check code. Below we will try to use PHP language to complete this work. It may be used in PHP development, such as verifying whether the user's ID number is correct.
Suppose the first 17 digits of a Chinese (Mainland) citizen’s ID card number are this: 44010221990101001 (Note: This person was born in 2199), then we will try to write a few lines of PHP code according to the above algorithm to complete the calculation of the check code. . In order to make it easier for everyone to understand, I used simpler statements, please see the code:
<?php //身份证号码前17位,可以从各种数据源中获得(如数据库、用户提交的表单等) $body = '44010221990101001'; //加权因子 $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //校验码串 $ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); //按顺序循环处理前17位 for ($i = 0;$i < 17;$i++) { //提取前17位的其中一位,并将变量类型转为实数 $b = (int) $body{$i}; //提取相应的加权因子 $w = $wi[$i]; //把从身份证号码中提取的一位数字和加权因子相乘,并累加 $sigma += $b * $w; } //计算序号 $number = $sigma % 11; //按照序号从校验码串中提取相应的字符。 $check_number = $ai[$number]; //输出 echo $body.$check_number; ?>
After running the above code, it can be calculated that the verification code of the ID card is 9. You can try using the first 17 digits of your ID card.
If you understand the above example, you can merge some statements of this code, remove unnecessary variables, and optimize to get the following code:
<?php $body = '44010221990101001'; $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); $ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); for ($i = 0;$i < 17;$i++) { $sigma += ((int) $body{$i}) * $wi[$i]; } echo $body.$ai[($sigma % 11)]; ?>
The above is the PHP ID card verification code calculation method introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the Script House website!