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

How to use terminal within the Sublime Text editor?

Sublime Text is primarily a text editor and does not have a built-in terminal like some other integrated development environments (IDEs) do. However, you can use the terminal from within Sublime Text by installing a package called Terminal and Terminus . To use the terminal in Sublime Text using Terminal package, follow these steps: Install Package Control (if you haven't already): Open Sublime Text. Press Ctrl + (backtick) to open the Sublime Text console. Copy and paste the installation code for Package Control from the official website: https://packagecontrol.io/installation Press Enter to execute the code. Wait for Package Control to install. Install the "Terminal" package: Press Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac) to open the command palette. Type "Package Control: Install Package" and select it from the command palette. In the package list, type "Terminal" and select the "Terminal" package to install it. Open t...

What is null pointer dereferences in Rust?

In Rust, null pointer dereferences, also known as null pointer errors or null reference errors, refer to situations where a program attempts to access or dereference a null or uninitialized pointer. However, Rust's ownership and borrowing system and its lack of null pointers make null pointer dereferences virtually non-existent.  Rust's approach to null safety revolves around the concept of ownership and borrowing, which eliminates the need for null pointers and effectively prevents null pointer dereferences at compile-time. Instead of allowing null values, Rust uses the `Option` type to represent the presence or absence of a value.  The `Option` type is an enum with two variants: `Some(value)` to represent the presence of a value, and `None` to represent the absence of a value. By using `Option` types, Rust enforces explicit handling of potentially missing values, ensuring that developers handle the absence case explicitly, rather than encountering unexpected null pointer der...

How to take user input from terminal(stdin) in Rust?

In Rust, you can use the std::io module from the standard library to read input from the user. Here's an example that demonstrates how to get input from the user: use std::io; fn main() { // Create a new instance of `std::io::stdin` for reading user input let mut input = String::new(); // Prompt the user for input println!("Enter your name:"); // Read input from the user io::stdin() .read_line(&mut input) .expect("Failed to read line"); // Trim any trailing whitespace or newlines from the input let name = input.trim(); // Display the user's input println!("Hello, {}!", name); } In this example, we create a mutable String variable named input to store the user's input. We then use the std::io::stdin() function to obtain a handle to the standard input stream. Next, we call the read_line() method on the input stream, passing a mutable reference to the input variable. The r...