{jsonbody.com}

Top 200 PHP Interview Coding Problems & Solutions

Practice top PHP interview coding challenges with detailed code solutions, algorithms, OOP design patterns, and expert explanations.

Q1. Check if a number is prime

function isPrime($n) {
    if ($n <= 1) return false;
    for ($i = 2; $i <= sqrt($n); $i++) {
        if ($n % $i === 0) return false;
    }
    return true;
}
echo isPrime(11) ? 'Prime' : 'Not Prime';

Iterates from 2 up to the square root of the number to check for divisors efficiently in O(sqrt(N)) time.

Q2. Generate Fibonacci series up to N terms

function generateFibonacci($n) {
    $fib = [0, 1];
    for ($i = 2; $i < $n; $i++) {
        $fib[$i] = $fib[$i - 1] + $fib[$i - 2];
    }
    return array_slice($fib, 0, $n);
}
print_r(generateFibonacci(5));

Builds an array where each number is the sum of the two preceding ones.

Q3. Reverse a string without using built-in strrev()

function reverseString($str) {
    $rev = '';
    for ($i = mb_strlen($str) - 1; $i >= 0; $i--) {
        $rev .= mb_substr($str, $i, 1);
    }
    return $rev;
}
echo reverseString('hello');

Loops backward through the string character by character (multibyte safe via mb_substr).

Q4. Check if a string is a Palindrome

function isPalindrome($str) {
    $clean = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($str));
    return $clean === strrev($clean);
}
echo isPalindrome('A man, a plan, a canal: Panama') ? 'Yes' : 'No';

Cleans non-alphanumeric characters, converts to lowercase, and compares with its reversed equivalent.

Q5. Find factorial of a number iteratively and recursively

// Iterative
function factorialIterative($n) {
    $result = 1;
    for ($i = 2; $i <= $n; $i++) $result *= $i;
    return $result;
}

// Recursive
function factorialRecursive($n) {
    return ($n <= 1) ? 1 : $n * factorialRecursive($n - 1);
}

Shows both loop-based and recursive approaches to compute factorials.

Q6. Find the largest and smallest element in an array

function findMinMax($arr) {
    return [
        'min' => min($arr),
        'max' => max($arr)
    ];
}
print_r(findMinMax([4, 2, 9, 1, 5]));

Utilizes built-in min() and max() functions to evaluate array boundaries.

Q7. Find the second largest number in an array

function secondLargest($arr) {
    $arr = array_unique($arr);
    rsort($arr);
    return $arr[1] ?? null;
}
echo secondLargest([10, 5, 20, 20, 8]);

Removes duplicates, sorts descending, and retrieves index 1.

Q8. Count occurrences of each character in a string

function countChars($str) {
    return count_chars($str, 1);
}
print_r(count_chars('hello', 1));

Uses count_chars with mode 1 to return an associative array of byte-value frequencies.

Q9. Count occurrences of words in a sentence

function countWords($sentence) {
    $words = str_word_count(strtolower($sentence), 1);
    return array_count_values($words);
}
print_r(countWords('PHP is great and PHP is powerful'));

Extracts words into an array and tallies frequencies using array_count_values.

Q10. Remove duplicates from an array without array_unique()

function removeDuplicates($arr) {
    $result = [];
    foreach ($arr as $val) {
        if (!in_array($val, $result, true)) {
            $result[] = $val;
        }
    }
    return $result;
}
print_r(removeDuplicates([1, 2, 2, 3, 4, 4]));

Iterates through the array and stores unique elements in a new result array.

Q11. Merge two sorted arrays into a single sorted array

function mergeSortedArrays($a, $b) {
    $merged = array_merge($a, $b);
    sort($merged);
    return $merged;
}
print_r(mergeSortedArrays([1, 3, 5], [2, 4, 6]));

Combines arrays and sorts them in ascending order.

Q12. Find the intersection and union of two arrays

function arrayOperations($a, $b) {
    return [
        'union' => array_unique(array_merge($a, $b)),
        'intersection' => array_intersect($a, $b)
    ];
}
print_r(arrayOperations([1, 2, 3], [2, 3, 4]));

Calculates union and intersection using native array utility functions.

Q13. Rotate an array to the left by K positions

function rotateLeft($arr, $k) {
    $k = $k % count($arr);
    return array_merge(array_slice($arr, $k), array_slice($arr, 0, $k));
}
print_r(rotateLeft([1, 2, 3, 4, 5], 2));

Slices the array at position K and concatenates the two parts.

Q14. Validate a balanced parentheses string

function isValidParentheses($str) {
    $stack = [];
    $map = [')' => '(', '}' => '{', ']' => '['];
    for ($i = 0; $i < strlen($str); $i++) {
        $char = $str[$i];
        if (in_array($char, $map)) {
            array_push($stack, $char);
        } elseif (isset($map[$char])) {
            if (array_pop($stack) !== $map[$char]) return false;
        }
    }
    return empty($stack);
}
echo isValidParentheses('{[()]}') ? 'Valid' : 'Invalid';

Uses a stack array to verify matching open and close brackets.

Q15. Find the missing number in an array of 1 to N

function findMissingNumber($arr, $n) {
    $expectedSum = ($n * ($n + 1)) / 2;
    $actualSum = array_sum($arr);
    return $expectedSum - $actualSum;
}
echo findMissingNumber([1, 2, 4, 5], 5);

Uses the arithmetic progression sum formula minus actual array sum.

Q16. Group an array of associative records by a specific key

function groupByCategory($arr, $key) {
    $grouped = [];
    foreach ($arr as $item) {
        $grouped[$item[$key]][] = $item;
    }
    return $grouped;
}

Iterates and categorizes items into sub-arrays keyed by a shared attribute.

Q17. Flatten a multidimensional array

function flattenArray($array) {
    $return = [];
    array_walk_recursive($array, function($a) use (&$return) {
        $return[] = $a;
    });
    return $return;
}
print_r(flattenArray([1, [2, [3, 4], 5]]));

Uses array_walk_recursive to flatten deeply nested arrays into a single level.

Q18. Find the first non-repeating character in a string

function firstNonRepeatingChar($str) {
    $counts = array_count_values(str_split($str));
    foreach ($counts as $char => $count) {
        if ($count === 1) return $char;
    }
    return null;
}
echo firstNonRepeatingChar('swiss');

Tallies character counts and returns the first key with frequency equal to 1.

Q19. Implement binary search in PHP

function binarySearch($arr, $target) {
    $low = 0;
    $high = count($arr) - 1;
    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);
        if ($arr[$mid] == $target) return $mid;
        if ($arr[$mid] < $target) $low = $mid + 1;
        else $high = $mid - 1;
    }
    return -1;
}
echo binarySearch([1, 3, 5, 7, 9], 5);

Divide-and-conquer search algorithm operating on sorted arrays in O(log N) time.

Q20. Implement bubble sort algorithm

function bubbleSort($arr) {
    $n = count($arr);
    for ($i = 0; $i < $n; $i++) {
        for ($j = 0; $j < $n - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}
print_r(bubbleSort([64, 34, 25, 12, 22]));

Repeatedly swaps adjacent elements if they are in the wrong order.

Q21. Check if a year is a Leap Year

function isLeapYear($year) {
    return ($year % 4 === 0 && $year % 100 !== 0) || ($year % 400 === 0);
}
echo isLeapYear(2024) ? 'Leap' : 'Not Leap';

Applies standard Gregorian calendar leap year validation rules.

Q22. Find Armstrong number

function isArmstrong($num) {
    $sum = 0;
    $temp = $num;
    $digits = strlen((string)$num);
    while ($temp > 0) {
        $rem = $temp % 10;
        $sum += pow($rem, $digits);
        $temp = (int)($temp / 10);
    }
    return $sum === $num;
}
echo isArmstrong(153) ? 'Armstrong' : 'Not';

Computes the sum of its digits each raised to the power of the total number of digits.

Q23. Convert decimal to binary without decbin()

function decimalToBinary($n) {
    $binary = '';
    while ($n > 0) {
        $binary = ($n % 2) . $binary;
        $n = (int)($n / 2);
    }
    return $binary === '' ? '0' : $binary;
}
echo decimalToBinary(10);

Repeatedly divides by 2 and prepends the remainders.

Q24. Find Greatest Common Divisor (GCD) / HCF

function findGCD($a, $b) {
    while ($b !== 0) {
        $temp = $b;
        $b = $a % $b;
        $a = $temp;
    }
    return $a;
}
echo findGCD(54, 24);

Implements the Euclidean algorithm for GCD calculation.

Q25. Find Least Common Multiple (LCM)

function findLCM($a, $b) {
    return ($a * $b) / findGCD($a, $b);
}
echo findLCM(12, 15);

Calculates LCM using the product of two numbers divided by their GCD.

Q26. Calculate power of a number without pow()

function calculatePower($base, $exp) {
    $res = 1;
    for ($i = 0; $i < $exp; $i++) {
        $res *= $base;
    }
    return $res;
}
echo calculatePower(2, 4);

Multiplies base iteratively up to exponent count.

Q27. Find median of an array

function findMedian($arr) {
    sort($arr);
    $count = count($arr);
    $mid = floor($count / 2);
    if ($count % 2 === 0) {
        return ($arr[$mid - 1] + $arr[$mid]) / 2;
    }
    return $arr[$mid];
}
echo findMedian([3, 1, 4, 2, 5]);

Sorts the array and evaluates the middle index value.

Q28. Find mode (most frequent element) in an array

function findMode($arr) {
    $freq = array_count_values($arr);
    arsort($freq);
    return array_key_first($freq);
}
echo findMode([1, 2, 2, 3, 3, 3, 4]);

Counts frequencies, sorts descending, and retrieves the top key.

Q29. Remove all whitespace from a string

function removeWhitespace($str) {
    return preg_replace('/\s+/', '', $str);
}
echo removeWhitespace('  Hello   World  ');

Uses regular expression to strip all spaces and tabs.

Q30. Capitalize first letter of every word

function titleCase($str) {
    return ucwords(strtolower($str));
}
echo titleCase('php interview questions');

Normalizes case and capitalizes each word boundary.

Q31. Find longest word in a sentence

function longestWord($sentence) {
    $words = str_word_count($sentence, 1);
    usort($words, fn($a, $b) => strlen($b) - strlen($a));
    return $words[0] ?? '';
}
echo longestWord('The quick brown fox jumps');

Extracts words and sorts them by string length descending.

Q32. Swap two variables without using a third variable

$a = 5; $b = 10;
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
// $a is now 10, $b is 5

Mathematical swapping technique using addition and subtraction.

Q33. Check if a number is a power of two

function isPowerOfTwo($n) {
    return $n > 0 && ($n & ($n - 1)) === 0;
}
echo isPowerOfTwo(16) ? 'Yes' : 'No';

Bitwise operation check evaluating powers of 2.

Q34. Count vowels and consonants in a string

function countVowelsAndConsonants($str) {
    $str = strtolower($str);
    preg_match_all('/[aeiou]/', $str, $v);
    preg_match_all('/[b-df-hj-np-tv-z]/', $str, $c);
    return ['vowels' => count($v[0]), 'consonants' => count($c[0])];
}

Uses regex matching patterns to segregate vowel and consonant counts.

Q35. Reverse words order in a sentence

function reverseWords($sentence) {
    $words = explode(' ', trim($sentence));
    return implode(' ', array_reverse($words));
}
echo reverseWords('Hello World from PHP');

Explodes sentence into words array, reverses array order, and implodes back.

Q36. Find all subsets / power set of an array

function powerSet($arr) {
    $results = [[]];
    foreach ($arr as $element) {
        foreach ($results as $combination) {
            $results[] = array_merge([$element], $combination);
        }
    }
    return $results;
}

Generates all possible combinations subsets iteratively.

Q37. Verify if two strings are anagrams

function areAnagrams($s1, $s2) {
    $arr1 = str_split(strtolower(preg_replace('/[^a-z]/', '', $s1)));
    $arr2 = str_split(strtolower(preg_replace('/[^a-z]/', '', $s2)));
    sort($arr1); sort($arr2);
    return $arr1 === $arr2;
}
echo areAnagrams('listen', 'silent') ? 'Anagram' : 'Not';

Normalizes, splits into character arrays, sorts, and compares.

Q38. Find common characters shared between two strings

function commonChars($s1, $s2) {
    $arr1 = count_chars($s1, 1);
    $arr2 = count_chars($s2, 1);
    $common = [];
    foreach ($arr1 as $char => $count) {
        if (isset($arr2[$char])) {
            $common[] = str_repeat(chr($char), min($count, $arr2[$char]));
        }
    }
    return implode('', $common);
}

Intersects character frequency maps between strings.

Q39. Check if array is sorted in ascending order

function isSortedAsc($arr) {
    $n = count($arr);
    for ($i = 0; $i < $n - 1; $i++) {
        if ($arr[$i] > $arr[$i + 1]) return false;
    }
    return true;
}
echo isSortedAsc([1, 2, 3, 4]) ? 'Sorted' : 'Not';

Scans adjacent array elements to verify ascending monotonicity.

Q40. Find duplicate values in an array

function findDuplicates($arr) {
    $counts = array_count_values($arr);
    return array_keys(array_filter($counts, fn($c) => $c > 1));
}
print_r(findDuplicates([1, 2, 3, 2, 4, 5, 1]));

Filters frequency counts for values greater than 1.

Q41. Matrix addition of two 2D arrays

function addMatrices($A, $B) {
    $rows = count($A);
    $cols = count($A[0]);
    $C = [];
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            $C[$i][$j] = $A[$i][$j] + $B[$i][$j];
        }
    }
    return $C;
}

Adds corresponding elements across two matrices.

Q42. Transpose a 2D Matrix

function transposeMatrix($matrix) {
    $transposed = [];
    foreach ($matrix as $i => $row) {
        foreach ($row as $j => $val) {
            $transposed[$j][$i] = $val;
        }
    }
    return $transposed;
}

Swaps matrix rows and columns.

Q43. Find sum of diagonal elements in a square matrix

function diagonalSum($matrix) {
    $sum = 0;
    $n = count($matrix);
    for ($i = 0; $i < $n; $i++) {
        $sum += $matrix[$i][$i];
    }
    return $sum;
}
echo diagonalSum([[1,2],[3,4]]);

Sums elements where row index equals column index.

Q44. Check if a string rotation is valid

function isRotation($s1, $s2) {
    return strlen($s1) === strlen($s2) && strpos($s1 . $s1, $s2) !== false;
}
echo isRotation('waterbottle', 'erbottlewat') ? 'Yes' : 'No';

Concatenates string with itself to verify cyclic rotation substring.

Q45. Compress string with character counts (Run-Length Encoding)

function compressString($str) {
    $res = '';
    $len = strlen($str);
    for ($i = 0; $i < $len; $i++) {
        $count = 1;
        while ($i + 1 < $len && $str[$i] === $str[$i + 1]) {
            $count++;
            $i++;
        }
        $res .= $str[$i] . $count;
    }
    return $res;
}
echo compressString('aabcccccaaa');

Counts consecutive repeating characters to compress string format.

Q46. Find intersection point of two arrays without duplicates

function fastIntersection($a, $b) {
    return array_values(array_intersect($a, $b));
}

Wraps array_intersect and re-indexes array values.

Q47. Move all zeros to the end of an array

function moveZerosToEnd($arr) {
    $nonZeros = array_filter($arr, fn($v) => $v !== 0);
    $zeros = array_fill(0, count($arr) - count($nonZeros), 0);
    return array_merge(array_values($nonZeros), $zeros);
}
print_r(moveZerosToEnd([0, 1, 0, 3, 12]));

Filters non-zero elements and appends zero padding to match original count.

Q48. Find the maximum subarray sum (Kadane's Algorithm)

function maxSubArraySum($arr) {
    $maxSoFar = $arr[0];
    $currMax = $arr[0];
    for ($i = 1; $i < count($arr); $i++) {
        $currMax = max($arr[$i], $currMax + $arr[$i]);
        $maxSoFar = max($maxSoFar, $currMax);
    }
    return $maxSoFar;
}
echo maxSubArraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4]);

Computes the maximum contiguous subarray sum in O(N) time.

Q49. Find missing numbers in a sequence range

function findMissingRange($arr, $min, $max) {
    $full = range($min, $max);
    return array_diff($full, $arr);
}
print_r(findMissingRange([1, 2, 4, 6], 1, 6));

Computes array difference between complete range set and existing items.

Q50. Convert snake_case to camelCase

function snakeToCamel($str) {
    return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
echo snakeToCamel('hello_world_php');

Replaces underscores with spaces, capitalizes words, and lowercases first character.

Q51. Convert camelCase to snake_case

function camelToSnake($str) {
    return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $str));
}
echo camelToSnake('helloWorldPhp');

Inserts underscores before uppercase characters and lowercases string.

Q52. Extract domain name from a URL string

function getDomain($url) {
    $parsed = parse_url($url);
    return $parsed['host'] ?? '';
}
echo getDomain('https://www.jsonbody.com/change-password');

Uses parse_url native function to extract host domain components.

Q53. Generate random alphanumeric secure token

function generateToken($length = 32) {
    return bin2hex(random_bytes($length / 2));
}
echo generateToken(16);

Generates cryptographically secure pseudo-random cryptographic bytes.

Q54. Truncate string with ellipsis

function truncateString($str, $limit) {
    return mb_strlen($str) > $limit ? mb_substr($str, 0, $limit) . '...' : $str;
}
echo truncateString('Long interview text description', 10);

Slices multi-byte strings safely and appends truncation dots.

Q55. Mask email address for privacy

function maskEmail($email) {
    [$name, $domain] = explode('@', $email);
    $maskedName = substr($name, 0, 2) . str_repeat('*', max(0, strlen($name) - 2));
    return $maskedName . '@' . $domain;
}
echo maskEmail('developer@jsonbody.com');

Masks characters in email username prefix while preserving domain.

Q56. Check if IP address is valid IPv4

function isValidIPv4($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}
echo isValidIPv4('192.168.1.1') ? 'Valid' : 'Invalid';

Uses filter_var validation flags to check IPv4 formatting.

Q57. Convert associative array to query string

function arrayToQueryString(array $params) {
    return http_build_query($params);
}
echo arrayToQueryString(['search' => 'php', 'page' => 2]);

Encodes key-value pairs into URL-encoded query strings.

Q58. Extract query parameters from URL string

function getQueryParams($url) {
    $query = parse_url($url, PHP_URL_QUERY);
    parse_str($query, $params);
    return $params;
}
print_r(getQueryParams('https://site.com/?id=5&name=test'));

Parses URL query strings into an associative parameters array.

Q59. Shuffle array elements randomly

function customShuffle(array $arr) {
    shuffle($arr);
    return $arr;
}
print_r(customShuffle([1, 2, 3, 4, 5]));

Randomizes array element positions using built-in shuffle.

Q60. Chunk array into smaller arrays of specified size

function chunkArray(array $arr, int $size) {
    return array_chunk($arr, $size);
}
print_r(chunkArray([1, 2, 3, 4, 5], 2));

Splits arrays into multi-dimensional chunks of fixed size.

Q61. Check if array is associative or indexed

function isAssoc(array $arr) {
    if ([] === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}
echo isAssoc(['a' => 1, 'b' => 2]) ? 'Assoc' : 'Indexed';

Compares array keys against sequential range indices.

Q62. Remove empty values from array

function compactArray(array $arr) {
    return array_values(array_filter($arr));
}
print_r(compactArray([0, 1, '', 2, null, false, 3]));

Filters out falsy values and re-indexes array sequence.

Q63. Find difference between two associative arrays recursively

function recursiveArrayDiff($arr1, $arr2) {
    $diff = [];
    foreach ($arr1 as $key => $value) {
        if (!array_key_exists($key, $arr2)) {
            $diff[$key] = $value;
        } elseif (is_array($value)) {
            $d = recursiveArrayDiff($value, $arr2[$key]);
            if ($d) $diff[$key] = $d;
        } elseif ($value !== $arr2[$key]) {
            $diff[$key] = $value;
        }
    }
    return $diff;
}

Performs recursive delta checks on deep arrays.

Q64. Pluck specific column values from multidimensional array

function pluckColumn(array $arr, string $column) {
    return array_column($arr, $column);
}
print_r(pluckColumn([['id'=>1, 'name'=>'John'], ['id'=>2, 'name'=>'Doe']], 'name'));

Extracts values from a single column in an array of records.

Q65. XML string to Associative Array converter

function xmlToArray(string $xmlString) {
    $xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    return json_decode($json, true);
}

Parses XML documents into associative PHP arrays via JSON bridge.

Q66. Convert array to formatted XML string

function arrayToXml(array $data, SimpleXMLElement &$xml) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $subnode = $xml->addChild(is_numeric($key) ? 'item' : $key);
            arrayToXml($value, $subnode);
        } else {
            $xml->addChild(is_numeric($key) ? 'item' : $key, htmlspecialchars($value));
        }
    }
}

Recursively builds XML node elements from array structures.

Q67. Human readable file size formatter

function formatBytes(int $bytes, int $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes, $precision) . ' ' . $units[$pow];
}
echo formatBytes(5000000);

Converts raw file byte sizes into readable KB, MB, or GB strings.

Q68. Generate slug from article title

function slugify(string $text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    return strtolower($text);
}
echo slugify('Top PHP Interview Questions & Solutions!');

Creates clean URL slugs by stripping special characters and transliterating unicode.

Q69. Check if string starts with specific substring

function startsWith(string $haystack, string $needle) {
    return str_starts_with($haystack, $needle);
}
echo startsWith('hello world', 'hello') ? 'Yes' : 'No';

Uses modern PHP str_starts_with function for prefix verification.

Q70. Check if string ends with specific substring

function endsWith(string $haystack, string $needle) {
    return str_ends_with($haystack, $needle);
}
echo endsWith('document.pdf', '.pdf') ? 'Yes' : 'No';

Uses modern PHP str_ends_with function for suffix verification.

Q71. Simple benchmark execution timer utility

class Benchmark {
    private static float $start;
    public static function start() { self::$start = microtime(true); }
    public static function end() {
        return (microtime(true) - self::$start) . ' seconds';
    }
}

Measures precise script execution duration for performance audits.

Q72. Validate strong password criteria

function isStrongPassword(string $password) {
    return strlen($password) >= 8 &&
           preg_match('/[A-Z]/', $password) &&
           preg_match('/[a-z]/', $password) &&
           preg_match('/[0-9]/', $password) &&
           preg_match('/[^a-zA-Z0-9]/', $password);
}
echo isStrongPassword('Secret@123') ? 'Strong' : 'Weak';

Enforces strict length, caps, lowercase, numbers, and symbol requirements.

Q73. Calculate age from birthdate string

function calculateAge(string $dob) {
    $birthDate = new DateTime($dob);
    $today = new DateTime('today');
    return $birthDate->diff($today)->y;
}
echo calculateAge('1995-06-15');

Computes exact age years using native DateTime diff intervals.

Q74. Get days remaining until target date

function daysUntil(string $targetDate) {
    $target = new DateTime($targetDate);
    $today = new DateTime('today');
    return $today->diff($target)->days;
}

Calculates day intervals until future targets.

Q75. Sanitize HTML input string against XSS

function sanitizeHtml(string $input) {
    return htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
echo sanitizeHtml('<script>alert("XSS")</script>');

Escapes special characters to prevent client script injection vulnerabilities.

Q76. Generate pagination offset and limit array

function getPagination(int $page, int $perPage, int $totalRecords) {
    $totalPages = ceil($totalRecords / $perPage);
    $page = max(1, min($page, $totalPages));
    $offset = ($page - 1) * $perPage;
    return ['limit' => $perPage, 'offset' => $offset, 'pages' => $totalPages];
}

Calculates database query pagination offsets and total page counts.

Q77. Highlight search keywords in text

function highlightKeyword(string $text, string $keyword) {
    return preg_replace('/(' . preg_quote($keyword, '/') . ')/i', '<mark>$1</mark>', $text);
}

Wraps matched keyword occurrences in HTML mark tags case-insensitively.

Q78. Convert camelCase array keys to snake_case

function keysCamelToSnake(array $array) {
    $result = [];
    foreach ($array as $key => $value) {
        $newKey = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key));
        $result[$newKey] = is_array($value) ? keysCamelToSnake($value) : $value;
    }
    return $result;
}

Recursively normalizes all associative array keys from camelCase to snake_case.

Q79. Convert snake_case array keys to camelCase

function keysSnakeToCamel(array $array) {
    $result = [];
    foreach ($array as $key => $value) {
        $newKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
        $result[$newKey] = is_array($value) ? keysSnakeToCamel($value) : $value;
    }
    return $result;
}

Recursively transforms array keys from snake_case into camelCase.

Q80. Generate a random color HEX code

function randomHexColor() {
    return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
echo randomHexColor();

Generates random hexadecimal color codes for dynamic UI testing.

Q81. Implement a Thread-Safe Singleton Pattern

class Singleton {
    private static ?Singleton $instance = null;
    private function __construct() {}
    public static function getInstance(): Singleton {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
    private function __clone() {}
}

Restricts instantiation to a single object instance globally.

Q82. Implement Factory Design Pattern

interface Logger { public function log($msg); }
class FileLogger implements Logger { public function log($msg) { /* write */ } }
class LogFactory {
    public static function make($type): Logger {
        if ($type === 'file') return new FileLogger();
        throw new Exception('Invalid type');
    }
}

Delegates object creation logic to a dedicated factory class.

Q83. Implement Observer Design Pattern

interface Observer { public function update($data); }
class Subject {
    private array $observers = [];
    public function attach(Observer $o) { $this->observers[] = $o; }
    public function notify($data) { foreach ($this->observers as $o) $o->update($data); }
}

Allows objects to notify dependents about state changes automatically.

Q84. Implement Strategy Design Pattern

interface PaymentStrategy { public function pay($amount);
}
class PayPal implements PaymentStrategy { public function pay($amount) { /* ... */ } }
class ShoppingCart {
    public function checkout(PaymentStrategy $strategy, $amount) {
        return $strategy->pay($amount);
    }
}

Encapsulates interchangeable algorithms behind a common interface.

Q85. Implement a Custom Autoloader using PSR-4 standard

spl_autoload_register(function ($class) {
    $prefix = 'App\\';
    $base_dir = __DIR__ . '/src/';
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) return;
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) require $file;
});

Automatically resolves and loads PHP class files based on namespace paths.

Q86. Implement Adapter Design Pattern

interface Target { public function request(); }
class Adaptee { public function specificRequest() { return 'Data'; } }
class Adapter implements Target {
    private Adaptee $adaptee;
    public function __construct(Adaptee $adaptee) { $this->adaptee = $adaptee; }
    public function request() { return $this->adaptee->specificRequest(); }
}

Converts the interface of a class into another interface clients expect.

Q87. Implement Decorator Design Pattern

interface Coffee { public function cost(); }
class SimpleCoffee implements Coffee { public function cost() { return 5; } }
class MilkDecorator implements Coffee {
    protected Coffee $coffee;
    public function __construct(Coffee $c) { $this->coffee = $c; }
    public function cost() { return $this->coffee->cost() + 2; }
}

Dynamically adds responsibilities to objects without altering their structure.

Q88. Implement Builder Design Pattern

class House {
    public string $walls;
    public string $roof;
}
class HouseBuilder {
    private House $house;
    public function __construct() { $this->house = new House(); }
    public function buildWalls($w) { $this->house->walls = $w; return $this; }
    public function buildRoof($r) { $this->house->roof = $r; return $this; }
    public function getResult() { return $this->house; }
}

Constructs complex objects step by step using fluent chaining.

Q89. Implement Prototype Design Pattern

abstract class Prototype {
    public string $title;
    abstract public function __clone();
}
class Book extends Prototype {
    public function __clone() {}
}

Creates duplicate objects while keeping performance in mind via cloning.

Q90. Implement Facade Design Pattern

class CPU { public function freeze() {} }
class ComputerFacade {
    protected CPU $cpu;
    public function __construct() { $this->cpu = new CPU(); }
    public function start() { $this->cpu->freeze(); }
}

Provides a simplified unified interface to a complex subsystem of classes.

Q91. Implement Iterator Design Pattern via Iterator interface

class CustomCollection implements Iterator {
    private array $items = [];
    private int $index = 0;
    public function __construct(array $items) { $this->items = $items; }
    public function current() { return $this->items[$this->index]; }
    public function key() { return $this->index; }
    public function next() { ++$this->index; }
    public function rewind() { $this->index = 0; }
    public function valid() { return isset($this->items[$this->index]); }
}

Enables custom sequential traversal across container objects.

Q92. Implement Command Design Pattern

interface Command { public function execute(); }
class Light { public function turnOn() { echo 'Lit'; } }
class TurnOnCommand implements Command {
    private Light $light;
    public function __construct(Light $l) { $this->light = $l; }
    public function execute() { $this->light->turnOn(); }
}

Encapsulates a request as an object, letting parameterize clients.

Q93. Implement State Design Pattern

interface State { public function handle(); }
class ConcreteStateA implements State { public function handle() { return 'State A'; } }
class Context {
    private State $state;
    public function setState(State $s) { $this->state = $s; }
    public function request() { return $this->state->handle(); }
}

Allows an object to alter its behavior when its internal state changes.

Q94. Implement Template Method Pattern

abstract class Game {
    abstract protected function initialize();
    abstract protected function startPlay();
    public final function play() { $this->initialize(); $this->startPlay(); }
}
class Chess extends Game {
    protected function initialize() {} 
    protected function startPlay() {}
}

Defines the skeleton of an algorithm in a method, deferring steps to subclasses.

Q95. Implement Dependency Injection Container class

class Container {
    private array $bindings = [];
    public function bind($abstract, $concrete) {
        $this->bindings[$abstract] = $concrete;
    }
    public function make($abstract) {
        $concrete = $this->bindings[$abstract];
        return new $concrete();
    }
}

Manages class binding resolutions and dependency instantiation.

Q96. Create custom Exception class with error code logging

class DatabaseConnectionException extends Exception {
    public function errorMessage() {
        return 'Error on line ' . $this->getLine() . ' in ' . $this->getFile() . ': ' . $this->getMessage();
    }
}

Extends core Exception to provide custom domain error messaging.

Q97. Implement Method Chaining Fluent Interface

class QueryBuilder {
    private string $query = '';
    public function select(string $table) { $this->query = "SELECT * FROM $table"; return $this; }
    public function where(string $condition) { $this->query .= " WHERE $condition"; return $this; }
    public function get() { return $this->query; }
}
echo (new QueryBuilder())->select('users')->where('id = 1')->get();

Returns $this from object methods to enable continuous fluent chaining.

Q98. Implement Object Cloning Deep Copy via __clone

class Address { public string $city; }
class Person {
    public string $name;
    public Address $address;
    public function __clone() {
        $this->address = clone $this->address;
    }
}

Performs deep cloning of nested object references during clone events.

Q99. Implement __get and __set dynamic properties wrapper

class DynamicModel {
    private array $data = [];
    public function __set($name, $value) { $this->data[$name] = $value; }
    public function __get($name) { return $this->data[$name] ?? null; }
}

Captures unassigned dynamic property calls into internal data arrays.

Q100. Implement __call magic method for dynamic method interception

class MethodProxy {
    public function __call(string $method, array $args) {
        return "Method $method called with " . count($args) . " arguments.";
    }
}
echo (new MethodProxy())->dynamicMethod('arg1', 'arg2');

Intercepts calls to missing or undefined class methods dynamically.

Q101. ${id}. Advanced PHP OOP and Design Pattern Challenge ${id}

class AdvancedComponent_${id} {
    private array $attributes = [];
    public function setAttribute(string $key, $value): self {
        $this->attributes[$key] = $value;
        return $this;
    }
    public function getAttribute(string $key) {
        return $this->attributes[$key] ?? null;
    }
}
$comp = (new AdvancedComponent_${id}())->setAttribute('status', 'active');

Object-oriented architectural pattern implementation and clean code solution for interview challenge number ${id}.

Q102. Secure Database connection and Prepared Statement via PDO

try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    error_log($e->getMessage());
}

Establishes secure PDO connection and executes safe parameterized queries.

Q103. Implement secure file upload handling

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileTmp = $_FILES['file']['tmp_name'];
    $fileName = bin2hex(random_bytes(16)) . '.jpg';
    $destination = './uploads/' . $fileName;
    $mime = mime_content_type($fileTmp);
    if (in_array($mime, ['image/jpeg', 'image/png'])) {
        move_uploaded_file($fileTmp, $destination);
    }
}

Validates MIME types, generates cryptographically secure filenames, and moves uploads securely.

Q104. Read a massive CSV file line by line using generators

function readCSV($filename) {
    $file = fopen($filename, 'r');
    while (($line = fgetcsv($file)) !== false) {
        yield $line;
    }
    fclose($file);
}
foreach (readCSV('large.csv') as $row) {
    // process row without memory overflow
}

Streams large files line by line using generators to keep RAM consumption minimal.

Q105. Implement a simple Token Bucket Rate Limiter using Redis

function checkRateLimit($redis, $ip, $limit = 60, $window = 60) {
    $key = "rate:$ip";
    $current = $redis->get($key);
    if (!$current) {
        $redis->setex($key, $window, 1);
        return true;
    }
    if ($current < $limit) {
        $redis->incr($key);
        return true;
    }
    return false;
}

Tracks and enforces client request thresholds per time window using Redis.

Q106. Generate and Verify JSON Web Token (JWT) manually

// Using firebase/php-jwt library
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$payload = ['sub' => 123, 'iat' => time(), 'exp' => time() + 3600];
$jwt = JWT::encode($payload, 'secret_key', 'HS256');
$decoded = JWT::decode($jwt, new Key('secret_key', 'HS256'));

Issues and validates cryptographically signed tokens for stateless authentication.

Q107. Implement database transaction rollback block with PDO

try {
    $pdo->beginTransaction();
    $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    throw $e;
}

Ensures atomic multi-query execution with automatic rollback on failure.

Q108. Write custom error logger handler function

function customErrorLog(string $message, string $level = 'ERROR') {
    $date = date('Y-m-d H:i:s');
    $logMessage = "[$date] [$level]: $message" . PHP_EOL;
    file_put_contents(__DIR__ . '/app.log', $logMessage, FILE_APPEND | LOCK_EX);
}
customErrorLog('Database connection timed out');

Logs formatted messages securely into a local file with exclusive file locking.

Q109. Recursively delete folder and its contents

function deleteDirectory(string $dir) {
    if (!file_exists($dir)) return;
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        is_dir($path) ? deleteDirectory($path) : unlink($path);
    }
    rmdir($dir);
}

Recursively traverses directories to delete all nested files and folders.

Q110. Write data securely into JSON file storage

function writeJsonFile(string $filepath, array $data) {
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    file_put_contents($filepath, $json, LOCK_EX);
}
writeJsonFile('config.json', ['status' => true]);

Encodes array data safely into JSON files with exclusive locks.

Q111. Read and parse JSON file storage data safely

function readJsonFile(string $filepath) {
    if (!file_exists($filepath)) return null;
    $content = file_get_contents($filepath);
    return json_decode($content, true);
}

Safely reads and decodes JSON configuration files into associative arrays.