We seldom need a code to check whether the ISBN of book we are trying to search is a valid ISBN or not. So as to validate a provided ISBN we can use the below code for ISBN10 and ISBN13 respectively :
Code for checking validity of ISBN10 :
function isValidIsbn10($isbn){
if(strlen($isbn)!==10) return false;
$check = 0;
for ($i = 0; $i < 10; $i++) {
if ('x' === strtolower($isbn[$i])) {
$check += 10 * (10 - $i);
} elseif (is_numeric($isbn[$i])) {
$check += (int)$isbn[$i] * (10 - $i);
} else {
return false;
}
}
return (0 === ($check % 11)) ? 1 : false;
}
Code for checking validity of ISBN13 :
function isValidIsbn13($isbn){
if(strlen($isbn)!==13) return false;
$check = 0;
for ($i = 0; $i < 13; $i += 2) {
$check += (int)$isbn[$i];
}
for ($i = 1; $i < 12; $i += 2) {
$check += 3 * $isbn[$i];
}
return (0 === ($check % 10)) ? 2 : false;
}
0 Comment(s)