What are the considerations for handling validation of ISBN-10 and ISBN-13 numbers in PHP, including checksum validation?
When validating ISBN-10 and ISBN-13 numbers in PHP, it's important to consider the checksum validation to ensure the numbers are valid. For ISBN-10, the checksum is calculated using a weighted sum formula, while for ISBN-13, it uses a different algorithm. It's crucial to implement these checksum validations to ensure the integrity of the ISBN numbers.
function validateISBN10($isbn) {
$isbn = str_replace('-', '', $isbn);
if (!preg_match('/^\d{9}[\dX]$/', $isbn)) {
return false;
}
$sum = 0;
for ($i = 0; $i < 9; $i++) {
$sum += $isbn[$i] * (10 - $i);
}
$checksum = ($isbn[9] == 'X') ? 10 : $isbn[9];
return $sum % 11 == $checksum;
}
function validateISBN13($isbn) {
$isbn = str_replace('-', '', $isbn);
if (!preg_match('/^\d{13}$/', $isbn)) {
return false;
}
$sum = 0;
for ($i = 0; $i < 12; $i++) {
$sum += $isbn[$i] * (($i % 2 == 0) ? 1 : 3);
}
$checksum = 10 - $sum % 10;
return $checksum == $isbn[12];
}
$isbn10 = '0684856093';
$isbn13 = '9780132350884';
echo validateISBN10($isbn10) ? 'Valid ISBN-10' : 'Invalid ISBN-10'; // Output: Valid ISBN-10
echo "\n";
echo validateISBN13($isbn13) ? 'Valid ISBN-13' : 'Invalid ISBN-13'; // Output: Valid ISBN-13
Keywords
Related Questions
- What are the common pitfalls in PHP code that can lead to data not being inserted into a database?
- In what scenarios would using a recursive function be beneficial for processing text files in PHP, and how can it be implemented effectively in this context?
- What are the potential pitfalls of using arrays in PHP, especially when working with data from multiple tables?