PHP Multiple Choice Questions (MCQs) with Answers - The Ultimate Test for Web Developers

PHP: Hypertext Preprocessor

PHP is an open-source server-side scripting language that is used to generate dynamic web pages. PHP scripts are written between reserved PHP tags that allow programmers to embed PHP scripts within HTML pages. It is an interpreted language, which means scripts are parsed at run-time, rather than being compiled beforehand. It is executed on the server-side and the source code is not visible by the client.

PHP has various built-in functions that allow for fast development and is compatible with many popular databases. It also supports both procedural and object-oriented paradigms. All PHP statements end with a semi-colon and each PHP script must be enclosed in the reserved PHP tag.

Variables in PHP must begin with a "$" sign and are case-sensitive. PHP has globally and locally scoped variables, where global variables can be used anywhere and local variables are restricted to a function or class. Certain variable names are reserved by PHP, such as form variables ($_POST, $_GET) and server variables ($_SERVER).


//example variable declaration
$example_var = "Hello World"; 

//Echo statement to print out variable
echo $example_var;

In PHP, MCQs are used to assess knowledge of the language and its capabilities.

Full Form of PHP

The full form of PHP is Hypertext Preprocessor.

// Example code
$variable_name = "This is a PHP variable";
echo $variable_name; // Output: This is a PHP variable

PHP is a server-side scripting language used for web development. It can be embedded into HTML and is commonly used to create dynamic web pages.

Default File Extension of PHP

In PHP, the default file extension for web pages is .php. When PHP code is written inside a file with this extension, it is executed and the output is displayed on the web page.

Out of the given options, the correct file extension for PHP is option C) .php


Understanding PHP as a Server-Side Scripting Language

// PHP code example
if ($age < 18) {
  echo "Sorry, you are not old enough to access this content.";
} else {
  echo "Welcome to our website!";

PHP is a server-side scripting language that is widely used for web development. It runs on the server hosting a website, generates HTML code, and sends it to the user's web browser.

One of the advantages of using PHP is that it allows developers to create dynamic web pages that can display custom content for each user. PHP can also handle user input, interact with databases, and perform various server-side operations.

In the code example above, PHP is used to check the user's age and display a corresponding message on the web page. This is just one of the many things that PHP can be used for in web development.

Overall, PHP is a powerful and flexible language that is essential for building modern web applications. As a server-side language, it plays a critical role in delivering dynamic and interactive content to users.I'm sorry, but there is no information or options provided in your request. Can you please provide more context or details so I can better assist you?Code:

Equivalent of the statement

Given statement: $sub -= $sub

Equivalent statement: $sub = $sub - $sub

Total Ways to Print Output in PHP

There are two ways to print output in PHP, which are:





Therefore, the correct answer is A) Output can be printed in 2 ways i.e. echo and print.

Comparison between echo and print in terms of speed

Out of echo and print, echo is comparatively faster than print.

//example code to compare speed of echo and print $start_time = microtime(true); //start timer for($i=0;$i<100000;$i++){ echo "test"; } $end_time = microtime(true); //end timer $time_taken = $end_time - $start_time; //calculate time taken echo "Time taken for echo: ".$time_taken."
"; //display time taken for echo

$start_time = microtime(true); //start timer for($i=0;$i<100000;$i++){ print "test"; } $end_time = microtime(true); //end timer $time_taken = $end_time - $start_time; //calculate time taken echo "Time taken for print: ".$time_taken; //display time taken for print

As shown in the example code, echo is faster than print. However, the difference in speed may not be significant in most cases.

PHP Variable Naming Convention

In PHP, variable names must follow all of the following:

- Variable names must not start with a number

- Variable names should start with a letter or underscore

- Variable names can only contain letters, numbers, and underscores

- Variable names are case-sensitive

Therefore, the correct answer is (D) All of the above.

Is PHP Variable Case-Sensitive?

The answer is true. In PHP, variables are case-sensitive. This means that variables with the same name but different capitalization are considered separate variables. For example, $name and $Name would be two distinct variables.

PHP Variable Scope

In PHP, the scope of a variable refers to where the variable can be accessed in the code. There are three main types of variable scope in PHP:

1. Local Scope: Variables declared inside a function have local scope, meaning they can only be accessed within that function.

2. Global Scope: Variables declared outside of a function have global scope, meaning they can be accessed from any part of the code, including within functions.

3. Static Scope: Variables declared within a function as static have static scope, meaning they retain their value even after the function has been executed.

It is important to keep track of variable scope to avoid unexpected behavior and ensure that variables are only accessed where they are intended to be used.

Incorrect Data Type in PHP

Out of the given data types, the incorrect data type in PHP is void. It is not considered as a data type in PHP. The rest of the options, such as objects, null, and resources, are valid data types in PHP.

// Example of valid data types in PHP

// Object
class Person {
  public $name;
  public $age;

// Null
$var = null;

// Resource
$file = fopen("file.txt", "r");

Supported Looping Techniques in PHP

// Initialize a variable for the loop counter $count = 0;

// For loop for ($i = 0; $i < 10; $i++) { $count++; } // While loop while ($count < 20) { $count++; } // Do-while loop do { $count++; } while ($count < 30); // For-each loop $fruits = ['apple', 'banana', 'mango']; foreach ($fruits as $fruit) { echo $fruit; }

PHP supports four types of looping techniques - for, while, do-while, and for-each loop. These techniques allow developers to repeat a block of code multiple times based on specific conditions. The for loop is used when the number of iterations is known; while and do-while loops are used when the number of iterations is unknown. The for-each loop is used when iterating over items in an array or collection. By understanding and using these looping techniques, developers can make their code more efficient and effective.

Correcting and Optimizing a True or False Question on Do-While Loop

// The do-while loop executes a block of code at least once
// before evaluating the loop condition.
// Hence, it is an exit controlled loop.

// The correct answer is true.

boolean isExitControlledLoop = true;

While loops as Entry Control Loops

It is important to understand the fundamental characteristics of loops in programming. A loop is a set of instructions that keep running until the specified condition is met. There are two types of loops in programming languages, namely a while loop and a for loop. One of the most common misconceptions about loops is whether a while loop is an entry control loop or an exit control loop.

The answer is that a while loop is an entry control loop, which means that the statements within the block will be executed only if the condition is true. If it is false, then the loop is terminated immediately. A for loop, on the other hand, is an exit control loop, where the statements are executed at least once, and the loop continues until the specified condition is false.


// an example of a while loop
int i = 0;
while (i < 10) {
  cout << i << endl;

// an example of a for loop
for (int i = 0; i < 10; i++) {
  cout << i << endl;

Both loops will iterate through a block of code ten times, but the main difference is the way they are structured. The while loop checks the condition first before executing anything, while the for loop initializes a counter, has a condition, and increments the value each time the loop runs.

Identifying non-Built-In PHP Functions




, and


are all examples of built-in functions in PHP. On the other hand,


is not included in the pre-defined set of functions that PHP provides.

When it comes to file handling in PHP, there is a pair of file handling functions that come in hand with each other:




. The former is used to open a file and create a file pointer while the latter is used to close the file that's being pointed to by the file pointer. However,


is not a standardized PHP function.

Overall, the function not built-in is



Correct Keyword to Start a Function in PHP

In PHP, functions should start with the keyword "function".

//example of a function definition in PHP
function addNumbers($num1, $num2){
  $sum = $num1 + $num2;
  return $sum;

PHP Array Types

In PHP, there are three types of arrays: indexed arrays, associative arrays, and multidimensional arrays.

Indexed arrays are arrays with a numeric index assigned to each element.

Associative arrays are arrays with a string index assigned to each element.

Multidimensional arrays are arrays containing one or more arrays.

Knowing the type of array is important in PHP programming as it helps in determining the best method to implement a specific solution to a problem.

Index of PHP Arrays

In PHP, the index of an array starts with 0 by default. This means that the first element of the array will have an index of 0, the second element will have an index of 1, and so on.

//example of an array with 3 elements
$fruits = array("apple", "banana", "orange");

//accessing the elements of the array
echo $fruits[0]; //outputs "apple"
echo $fruits[1]; //outputs "banana"
echo $fruits[2]; //outputs "orange"

It is important to remember this when working with arrays in PHP to avoid any indexing errors.


The trim() function in PHP is used to remove any whitespace or other predefined characters from both sides of a given string. It does not remove uppercase or lowercase alphabets or underscores, only whitespace characters.

Alternative Terms for Objects

In programming, objects are also referred to as instances. They are created from classes and can be thought of as individual entities with their own unique properties and behaviors.

Creating Objects with the 'new' Keyword

In JavaScript, objects are created using the 'new' keyword. For example:

const myObject = new Object();

This creates a new object called 'myObject' using the Object() constructor function. You can also create objects using other constructor functions or object literals.

Constructor's Other Name

In the context of programming, constructors are also referred to as 'magic functions'.

class Car {
  constructor(make, model, year) {   //Example of a constructor function in JavaScript
    this.make = make;
    this.model = model;
    this.year = year;

Referring to Methods within a Class in Java

In Java, the keyword


is used to refer to methods within the class itself. This keyword refers to the current instance of the class. It is used to avoid naming conflicts between class variables and method parameters.

The other options given in the question,




, and


, are used to determine the access level of classes, methods, and variables within a program.

Introduction of Type Hinting in PHP

In PHP 5, type hinting was introduced which allows a developer to specify the expected data type of an argument in a function or method declaration. This helps to prevent bugs and makes the code more readable and self-documenting.

function exampleFunction(string $param1, int $param2) { <br>
    // code goes here<br>

In the above code, we have used type hinting to specify that the first parameter must be a string and the second parameter must be an integer.

Function that accepts any number of parameters

The correct function that accepts any number of parameters is



Finding Files with glob() Function in Python

In Python, the


function is used to find files by matching a specified pattern. This function returns a list of file names that match the provided pattern.

Here's an example of using


to find all the .txt files in a directory:

import glob

txt_files = glob.glob('*.txt')


This code will search the current working directory for all files with a .txt extension and return a list of file names that match the search pattern.

Other matching patterns can be used as well, such as searching for files that start with a certain prefix or end with a specific extension.

Note that


only works on files that are located within the directory or its subdirectories and not on files that are located outside of the specified directory.

Identifying the Function for Compressing a String

In PHP, the gzcompress() function is used to compress a given string. It applies the gzip content-encoding to the input string. The syntax for using the function is as follows:

gzcompress(string $data [, int $level = -1 ]): string

Here, the first parameter is the input string that needs to be compressed, and the second parameter, which is optional, specifies the compression level.

Sorting an Array in Descending Order Using rsort()

In PHP, the function used to sort an array in descending order is




$numbers = array(5, 3, 8, 1, 9, 2);
rsort($numbers); // sorts the array in descending order
print_r($numbers); // prints the sorted array


    [0] => 9
    [1] => 8
    [2] => 5
    [3] => 3
    [4] => 2
    [5] => 1

Correct Way to Invoke a Method

To invoke a method, we use the arrow operator "->" followed by the method name with parentheses "()". This is used for objects in PHP.


Option D is the correct way to invoke a method.

Preventing Method Override with Final Keyword

In Java, the `final` keyword can be used with a method to prevent it from being overridden by a subclass. This is a method scope that restricts the modification of the method signature. Once a method is marked as final, the subclass is not allowed to override that method, preventing any further modifications.

The option that prevents a method from being overridden by a subclass is



How Constructors are Recognized in PHP?

In PHP, constructors are recognized by the name


. This function is called automatically when an object of a class is created using the


keyword. The constructor function is used to initialize the object's properties and set their default values.

Example of a constructor in PHP:

class Car {
   public $model;
   public $year;

   function __construct($model, $year) {
      $this->model = $model;
      $this->year = $year;

In the example above, the


function takes two parameters




, and assigns them to the object's properties. This function will be called automatically when a new object of the


class is created.

To create a new object of the


class, we use the following syntax:

$my_car = new Car("Toyota", 2020);

This will create a new object of the


class with the


property set to "Toyota" and the


property set to 2020.

Method Chaining

Method chaining is a feature in programming that allows the calling of one or more methods or functions in a single instruction. This allows for concise and readable code by eliminating the need for intermediate variables.

For example:


The above code shows how to call multiple methods in a single instruction using method chaining.

Total Error Levels Available in PHP

There are 16 total error levels available in PHP.

        // Error reporting set to display all errors

        // Example of triggering an error
        $num = 10;
        if ($num > 5) {
            trigger_error("Number cannot be greater than 5", E_USER_WARNING);

The error_reporting() function is used to set the level of errors to be displayed. In the above code, we have set it to show all errors. We can also set it to show specific error levels as per our requirements. E_USER_WARNING is one of the error levels available in PHP.

What does error level E_ERROR denote?

In PHP, error level E_ERROR represents a fatal run-time error.

Identifying the option that invokes the exception class

throw new exception()

is the option that correctly invokes the exception class.

The other options have syntax errors or are using incorrect capitalization or spelling, and therefore will not compile:

new exception()

creates a new instance of the exception class but does not throw it.

throws new expection()

has a typo, as "expection" is misspelled and should be "exception". Also, "throws" is used to declare a method that may throw an exception, but it does not actually throw an exception itself.

New throws exception()

has incorrect capitalization in "New" and also has incorrect syntax order: the "throw" keyword should come before "new exception()".

Overall, option C)

throw new exception()

is the correct way to throw an instance of the exception class.

Generating Unique IDs in PHP

In PHP, the


function is used to generate unique IDs. This function generates a unique identifier based on the current time in microseconds (which ensures uniqueness) concatenated with a random number.

Example usage:

$id = uniqid();
echo $id;

This will output a unique ID in string format. The function also accepts a


parameter that can be used to add a prefix to the generated ID.

It is important to note that while


generates IDs that are unique enough for most purposes, they are not guaranteed to be completely unique in all scenarios. For more strict requirements, other methods such as UUIDs can be used.Code:





The `ord()` function in Python returns the Unicode code point of a character in the ASCII table. In this case, `'4'` is a character with a Unicode code point of 52 in the ASCII table. Therefore, the output of the code is 52.

Code Output Prediction

The code will output the following four lines:






The code probably looks something like this:

print(ord('H'))        # 72
print(ord('G') + 1)    # 72 + 1 = 73
print(ord("J") - 1)    # 75 - 1 = 74

The ord() function returns an integer representing the Unicode character. When you pass the character 'H' to the ord() function, it returns its ASCII value, which is 104. The ASCII value of 'G' is 103, and when you add 1 to it, you get 104. Similarly, when you subtract 1 from the ASCII value of 'J', which is 75, you get 74. Finally, the code probably has a typo, as it may have been trying to print the ASCII value of "í", which is not a single character but actually two (i and ´). This will generate a TypeError as shown in the output as "TypeError: ord() expected a character, but string of length 2 found".

Identifying the Function to Add a Value at the End of an Array

The function that adds a value at the end of an array is




    $my_array = array("apple", "banana", "orange");<br>
    array_push($my_array, "grapes"); // Adds "grapes" at the end of the array<br>
    print_r($my_array); // Output: Array ( [0] => apple [1] => banana [2] => orange [3] => grapes )

Understanding the output of ARRAY_PRODUCT

#include <iostream>
using namespace std;

int array_product(int arr[], int n)
    int product = 1;
    // Calculate the product of all elements in array
    for (int i = 0; i < n; i++) {
        product = product * arr[i];
    return product;
int main()
    int arr[] = { 2, 3, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << array_product(arr, n);
    return 0;

The output of this code is 120. This is because the


function calculates the product of all the elements in the given array. In this case, the given array is

{ 2, 3, 5, 4 }

, so the product of all its elements is 2 * 3 * 5 * 4, which equals 120. Finally, this product is printed to the console using



Sorting Arrays in Natural Order using natcasesort()

In PHP, the function


is used to sort arrays in a natural order. It is used to sort strings and is not case sensitive.

Here's an example:

$fruits = array("Banana", "orange", "Apple", "Mango");
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";


0 = Apple
1 = Banana
2 = Mango
3 = orange

In the above example, we have an array of fruits, which includes both uppercase and lowercase letters. We have used the


function to sort the array in a natural order. As a result, the array is sorted alphabetically, ignoring case, and the output is displayed using loop.

PHP Property Scope

In PHP, the property scope can be defined using one of the following keywords:

  • public
  • protected
  • private

The final keyword is not a property scope keyword, but rather a keyword that can be used to prevent a class or method from being overridden by a child class. Therefore, option D is the correct answer.

Determining Inheritance in Classes

In object-oriented programming, inheritance allows a new class to acquire the properties and methods of an existing class. When a child class inherits from a parent class, it can access all the methods and variables of the parent class. In this given question, the child class inherits from both a parent class and a base class.

class ParentClass:
    # parent class code

class BaseClass:
    # base class code

class ChildClass(ParentClass, BaseClass):
    # child class code

Implementing Overloading in PHP

In PHP, overloading can be implemented using the magic method __call(). This method is called when an object is called with a method that does not exist or is not accessible.

Here is an example of using overloading in PHP:

class OverloadedClass {
   public function __call($method, $arguments) {
      if (method_exists($this, $method.'_overload')) {
         return call_user_func_array(array($this, $method.'_overload'), $arguments);
      } else {
         throw new Exception("Method " . $method . " does not exist!");

   private function foo_overload($arg1, $arg2) {
      echo "foo was called with arguments: " . $arg1 . ", " . $arg2;

$obj = new OverloadedClass();
$obj->foo("arg1", "arg2");

In this example, we define the class OverloadedClass with a magic method __call(). This method checks if a method with the name of the called method exists, and if so, calls that method with the provided arguments. If the called method does not exist, an exception is thrown.

We then define a private method foo_overload() to be called when the foo() method is called. This method takes two arguments and simply echoes them to the screen.

Finally, we create a new instance of OverloadedClass and call the foo() method with two arguments. Since the foo() method does not exist, the __call() method is called and in turn calls the foo_overload() method with the provided arguments.

The output of this code will be:

foo was called with arguments: arg1, arg2

What is the Full Form of SPL?

The full form of SPL is Standard PHP Library.

// Example usage of SPL ArrayIterator class
$array = array("apple", "banana", "cherry");
$iterator = new ArrayIterator($array);
foreach ($iterator as $fruit) {
  echo $fruit;

The SPL library provides a collection of interfaces and classes for PHP extension writers. It also includes data structures such as doubly linked lists, stacks, and heaps. The SPL can be used to solve a wide variety of common problems in PHP programming.

Number of Data Filtering Types in PHP

PHP provides 2 types of filtering options for data:

1. Validation Filtering<br>
2. Sanitization Filtering

Option B is the correct answer as PHP has only 2 types of filtering.

Regular Expression for Matching Zero or One P

The regular expression that matches any expression string with zero or one P is:


This expression matches any string that has zero or one occurrence of the character 'P'.

What is POSIX?

POSIX is an abbreviation for Portable Operating System Interface, which is a set of standards designated to ensure compatibility between Unix-based operating systems. It was developed to encourage software interoperability across different Unix operating systems.

Therefore, B) Portable Operating system interface for Unix is the correct full form of POSIX.

Function to Convert a String to Uppercase

To convert a string to uppercase, we can use the


function in PHP. This function takes a string as input and returns the same string with all characters converted to uppercase.

//Example Usage<br>
$str = "hello world";<br>
$uppercase_str = strtoupper($str);<br>
echo $uppercase_str; //Output: HELLO WORLD<br>

Correct Usage of FILESIZE() Function

The FILESIZE() function is used to determine the size of a file. It returns the size of the file in bytes, not in KB, GB, or bits as the options suggest. Therefore, answer B is correct.

// Example usage of FILESIZE() function
int fileSize = FILESIZE("example.txt"); // Returns the size of "example.txt" in bytes

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.