PHP Coding Questions Solutions
PHP Coding Questions Solutions
Logic: Extract digits from end and build reversed number, then compare.
4. Common function to check palindrome for both string and number (no predefined functions)
Code:
function isPalindrome($input) {
$length = 0;
while (isset($input[$length])) { $length++; }
for ($i = 0; $i < $length / 2; $i++) {
if ($input[$i] != $input[$length - 1 - $i]) {
return false;
}
PHP Common Coding Questions & Answers
}
return true;
}
Explanation: Compare characters from start and end moving towards the center.
8. Reverse a number
Code:
$num = 1234;
$reverse = 0;
while ($num > 0) {
$digit = $num % 10;
$reverse = $reverse * 10 + $digit;
$num = intdiv($num, 10);
}
echo $reverse;