Skip to main content

List of latest and most asked PHP practical interviews questions & answers

Core PHP Practical Interview Questions

In this blog post I am sharing a list of some most asked PHP interview questions & answers. These are very useful and helpful for the freshers and experienced developer too. I have taken these questions from different sources and listed here at one place.

Ques. How to reverse a string without using any builtin function?

Ans:

 
<?php
  $str = 'My name is Diwakar Kumar';
  $len = 0;
  while(isset($str[$len]) != '')
      $len++;
  for($i = $len ; $i >= 0 ; $i--)
  {
      echo @$str[$i];
  }
Ques: Write a function to check if a given string is a palindrome or not.

Ans:

1st Method:

<?php	
function isPalindrome($str) {
    $str = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); // Convert to lowercase and remove non-alphanumeric characters
    $reverse = strrev($str); // Reverse the string
    return $str === $reverse; // Compare original and reversed string
}
2nd Method:

<?php
function isPalindrome($str) {
    $left = 0;
    $right = strlen($str) - 1;
    while ($left < $right) {
        if($str[$left] != $str[$right]) {
            return false;
        }
        $left++;
        $right--;
    }
    return true;
}

Ques: Write a function to calculate the factorial of a given number.

Ans:


<?php
function factorial($num) {
    if ($num <= 1) {
        return 1;
    } else {
        return $num * factorial($num - 1);
    }
}

Ques: Write a function to reverse a string.

Ans:


<?php
function reverseString($str) {
    $reverse = '';
    $length = strlen($str);
    for ($i = $length - 1; $i >= 0; $i--) {
        $reverse .= $str[$i];
    }
    return $reverse;
}

Ques: Write a function to check if a given number is prime or not.

Ans:


<?php
function isPrime($num) {
    if ($num <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }
    return true;
}

Ques: Write a function to reverse the order of words in a given string.

Ans:


<?php
function reverseWords($str) {
    $words = [];
    $word = '';
    for ($i = 0; $i < strlen($str); $i++) {
        if ($str[$i] == ' ') {
            $words[] = $word;
            $word = '';
        } else {
            $word .= $str[$i];
        }
    }
    $words[] = $word;
    $reverse = '';
    for ($i = count($words) - 1; $i >= 0; $i--) {
        $reverse .= $words[$i] . ' ';
    }
    return trim($reverse);
}

Ques: Write a function to find the maximum element in an array.

Ans:


<?php
function findMax($arr) {
    $max = $arr[0];
    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] > $max) {
            $max = $arr[$i];
        }
    }
    return $max;
}

Ques: Write a function to generate the Fibonacci sequence up to a given number.

Ans:


<?php
function fibonacci($num) {
    $fib = [0, 1];
    for ($i = 2; $i <= $num; $i++) {
        $fib[$i] = $fib[$i - 1] + $fib[$i - 2];
    }
    return $fib;
}

Ques: Write a function to remove all duplicate elements in an array.

Ans:


<?php
function removeDuplicates($arr) {
    $result = [];
    foreach ($arr as $value) {
        if (!in_array($value, $result)) {
            $result[] = $value;
        }
    }
    return $result;
}

Some pattern Questions:

Ques: Write a PHP program to print the following pattern.

1
2 3
4 5 6
7 8 9 10

Ans:


<?php
$num = 1;
for ($i = 1; $i <= 4; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $num . ' ';
        $num++;
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

*
**
***
****
*****

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo '*';
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

    *
   **
  ***
 ****
*****

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5 - $i; $j++) {
        echo ' ';
    }
    for ($k = 1; $k <= $i; $k++) {
        echo '*';
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

    1
   232
  34543
 4567654
567898765

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5 - $i; $j++) {
        echo ' ';
    }
    $num = $i;
    for ($k = 1; $k <= $i; $k++) {
        echo $num;
        $num++;
    }
    $num--;
    for ($l = 1; $l <= $i - 1; $l++) {
        $num--;
        echo $num;
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

A
BB
CCC
DDDD
EEEEE

Ans:


<?php
for ($i = 65; $i <= 69; $i++) {
    for ($j = 65; $j <= $i; $j++) {
        echo chr($i);
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

    A
   B C
  D E F
 G H I J
K L M N O

Ans:


<?php
$alpha = 65;
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5 - $i; $j++) {
        echo ' ';
    }
    for ($k = 1; $k <= $i; $k++) {
        echo chr($alpha) . ' ';
        $alpha++;
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

1
22
333
4444
55555

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $i;
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

A
BA
CBA
DCBA
EDCBA

Ans:


<?php
for ($i = 65; $i <= 69; $i++) {
    for ($j = $i; $j >= 65; $j--) {
        echo chr($j);
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

1
10
101
1010
10101

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        if ($j % 2 == 1) {
            echo '1';
        } else {
            echo '0';
        }
    }
    echo "\n";
}

Ques: Write a PHP program to print the following pattern.

*****
 ****
  ***
   **
    *

Ans:


<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= $i - 1; $j++) {
        echo ' ';
    }
    for ($k = 1; $k <= 6 - $i; $k++) {
        echo '*';
    }
    echo "\n";
}

Some problem solving questions:

Ques: Write a PHP program to find the largest and smallest elements in an array.

Ans:


<?php
$numbers = array(12, 6, 23, 8, 5, 19);
$smallest = $numbers[0];
$largest = $numbers[0];

foreach ($numbers as $num) {
    if ($num < $smallest) {
        $smallest = $num;
    }
    if ($num > $largest) {
        $largest = $num;
    }
}

echo "The smallest number in the array is: " . $smallest . "\n";
echo "The largest number in the array is: " . $largest . "\n";

Ques: Write a PHP program to find the sum of all even numbers and odds numbers in an array.

Ans:


<?php
$numbers = array(12, 6, 23, 8, 5, 19);
$even_sum = 0;
$odd_sum = 0;

foreach ($numbers as $num) {
    if ($num % 2 == 0) {
        $even_sum += $num;
    } else {
        $odd_sum += $num;
    }
}

echo "The sum of even numbers in the array is: " . $even_sum . "\n";
echo "The sum of odd numbers in the array is: " . $odd_sum . "\n";

Ques: Create a function that takes a string consisting of lowercase letters, uppercase letters and numbers and returns the string sorted in the same way as the examples below.

examples:
	sorting("eA2a1E") ➞ "aAeE12"
	sorting("Re4r") ➞ "erR4"
	sorting("6jnM31Q") ➞ "jMnQ136"
	sorting("846ZIbo") ➞ "bIoZ468"

Ans:


<?php
function sorting($str) {
    $lowercase = $uppercase = $numbers = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $char = $str[$i];
        if (ctype_lower($char)) {
            $lowercase .= $char;
        } else if (ctype_upper($char)) {
            $uppercase .= $char;
        } else if (ctype_digit($char)) {
            $numbers .= $char;
        }
    }
    $sortedStr = $lowercase . $uppercase . $numbers;
    return $sortedStr;
}
Note: I will try my best to keep this post updated.

Comments

Popular Posts

Different types of variables in Python with examples.

In Python, instance variables, static variables, and local variables are all different types of variables that serve different purposes within a program. Instance Variables: Instance variables are unique to each instance of a class. They are defined within a class's methods or the __init__ method and are accessed using the self keyword. Each instance of a class maintains its own copy of instance variables. These variables hold data specific to each object and can have different values for each instance of the class. Here's an example that demonstrates instance variables: class Person: def __init__(self, name, age): self.name = name # instance variable self.age = age # instance variable person1 = Person("Alice", 25) person2 = Person("Bob", 30) print(person1.name) # Output: Alice print(person2.name) # Output: Bob print(person1.age) # Output: 25 print(person2.age) # Output: 30  In the example above, name and a...

Python: Explain different types of methods with examples.

In Python, there are several types of methods that can be defined within a class. Each type of method serves a specific purpose and has different characteristics. The common types of methods in Python are: Instance Methods: Instance methods are the most commonly used methods in Python classes. They are defined within a class and are intended to operate on individual instances of the class. Instance methods have access to the instance variables and can modify their values. Here's an example that demonstrates an instance method: class Circle: def __init__(self, radius): self.radius = radius def calculate_area(self): return 3.14159 * self.radius ** 2 circle = Circle(5) print(circle.calculate_area()) # Output: 78.53975 In the above example, the calculate_area() method is an instance method that calculates the area of a circle based on its radius. It uses the instance variable self.radius to perform the calculation. Class Methods: Class methods are define...

Explain Buffer overflow in Rust with example.

Buffer overflow is a common type of vulnerability that occurs when a program writes data beyond the boundaries of a buffer, leading to memory corruption and potential security issues. However, Rust's memory safety guarantees and ownership system help prevent buffer overflows by detecting and preventing such errors at compile-time. Rust's string handling and array bounds checking provide built-in protection against buffer overflows. Here's an example of how Rust mitigates buffer overflow: fn main() { let mut buffer = [0u8; 4]; // Buffer of size 4 let data = [1u8, 2u8, 3u8, 4u8, 5u8]; // Data larger than buffer size // Uncommenting the line below would result in a compilation error. // buffer.copy_from_slice(&data); // Attempt to write data into buffer println!("Buffer: {:?}", buffer); }  In this example, we have a fixed-size buffer with a capacity of 4 bytes ([0u8; 4]) and a data array (data) with a length of 5 bytes. The intention i...