Top Answers to PHP Interview Questions

CTA

PHP is a broadly used open-source computer programming language that is best suited for building mobile APIs and dynamic websites. This PHP Interview Questions blog is curated by industry experts who have compiled a list of the most frequently asked PHP interview questions. Check out the following PHP interview questions that will help you master this programming language and land a lucrative job in this field:
Q1. Differentiate between static and dynamic websites.
Q2. What is PHP most used for?
Q3. Is PHP a case-sensitive scripting language?
Q4. What is the meaning of PEAR in PHP?
Q5. How is a PHP script executed?
Q6. What are the types of variables present in PHP?
Q7. What are the variable-naming rules you should follow in PHP?
Q8. What are the main characteristics of a PHP variable?
Q9. What is NULL in PHP?
Q10. How are constants defined in PHP?

The three categories into which this PHP Interview Questions blog is divided include the following:
1. Basic

2. Intermediate

3. Advanced

Go through this comprehensive tutorial to learn PHP:

Top 64 PHP Interview Questions and Answers

Learn for free ! Subscribe to our youtube Channel.

Basic Interview Questions

1. Differentiate between static and dynamic websites.

Static WebsiteDynamic Website
The content cannot be manipulated after the script is executedThe content can be changed even at the runtime
No way to change the content as it is predefinedThe content can be changed easily by manipulation and reloading

2. What is PHP most used for?

PHP has a plethora of uses for developers. Following are some of the most widely used concepts that PHP offers:

  • With PHP, it becomes very easy to provide restricted access to the required content of the website.
  • It allows users to access individual cookies and set them as per requirement.
  • Database manipulation operations, such as addition, deletion, and modification, can be done easily.
  • Form handling, alongside features that involve file handling concepts and email integration, is used widely.
  • The system module allows users to perform a variety of system functions such as open, read, write, etc.

3. Is PHP a case-sensitive scripting language?

The answer to this is both yes and no. Variables and their declaration in PHP are completely case sensitive while function names are not.

For example, user-defined functions in PHP can be defined in uppercase but later referred to in lowercase, and it would still function normally.

4. What is the meaning of PEAR in PHP?

PEAR stands for PHP Extension and Application Repository. It is one of the frameworks and acting repositories that host all of the reusable PHP components. Alongside containing some of the PHP libraries, it also provides you with a simple interface to automatically install packages.

5. How is a PHP script executed?

PHP scripts can be easily executed from the command-line interface (CLI). The syntax is as follows:
php filename.php

Here, filename refers to the file that contains scripts. The extension .php is needed alongside the filename.

6. What are the types of variables present in PHP?

There are eight primary data types in PHP as shown below:

  • Array: A named and ordered collection of data
  • Boolean: A logical value (True or False)
  • Double: Floating point numbers such as 5.1525
  • Integer: Whole numbers without a floating point
  • Object: An instance of classes, containing data and functions
  • NULL: A special data type, supporting only the NULL data
  • Resource: Special variables that hold references to external resources
  • String: A sequence of characters such as, “Hello learners!”

7. What are the variable-naming rules you should follow in PHP?

There are two main rules that you have to follow when naming a variable in PHP. They are as follows:

  • Variables can only begin with letters or underscores.
  • Special characters such as +, %, -, &, etc. cannot be used.

8. What are the main characteristics of a PHP variable?

Following are some of the most important aspects of the usage of variables in PHP:

  • Variables can be declared before the value assignment.
  • A variable value assignment happens using the ‘=’ operator.
  • Every variable in PHP is denoted with a $ (dollar) sign.
  • The value of a variable depends on its latest assigned value.
  • PHP variables are not intrinsic. There is no explicit declaration.

9. What is NULL in PHP?

NULL is a special data type in PHP used to denote the presence of only one value, NULL. You cannot assign any other value to it.

NULL is not case sensitive in PHP and can be declared in two ways as shown below:

$var = NULL:

Or

$var = null;

Both of the above syntaxes work fine in PHP.

10. How are constants defined in PHP?

Constants can be defined easily in PHP by making use of the define() function. This function is used to define and pull out the values of the constants easily.

Constants, as the name suggests, cannot be changed after definition. They do not require the PHP syntax of starting with the conventional $ sign.

11. What is the use of the constant() function in PHP?

The constant() function is used to retrieve the values predefined in a constant variable. It is used especially when you do not know the name of the variable.

12. What are the various constants predefined in PHP?

PHP consists of many constants, and following are some of the widely used ones:

  • _METHOD_: Represents the class name
  • _CLASS_: Returns the class name
  • _FUNCTION_: Denotes the function name
  • _LINE_: Denotes the working line number
  • _FILE_: Represents the path and the file name

13. Differentiate between variables and constants in PHP.

VariableConstant
Variables can have changed pathsConstants cannot be changed
The default scope is the current access scopeConstants can be accessed throughout without any scoping rules
The $ assignment is used for definitionConstants are defined using the define() function
Compulsory usage of the $ sign at the startNo need for the $ sign for constants

14. What does the phrase ‘PHP escape’ mean?

PHP escape is a mechanism that is used to tell the PHP parser that certain code elements are different from PHP code. This provides the basic means to differentiate a piece of PHP code from the other aspects of the program.

15. Differentiate between PHP4 and PHP5.

PHP4PHP5
No support for static methodsAllows the usage of static methods
Abstract classes cannot be declaredAbstract classes can be declared
The method of call-by-value is usedThe method of call-by-reference is used
Constructors can have class namesConstructors have separate names

16. How are two objects compared in PHP?

PHP provides you with the ‘==’ operator, which is used to compare two objects at a time. This is used to check if there is a common presence of attributes and values between the objects in comparison.

The ‘===’ operator is also used to compare if both objects in consideration are referencing to the same class.

17. What is the meaning of break and continue statements in PHP?

Break: This statement is used in a looping construct to terminate the execution of the iteration and to immediately execute the next snippet of code outside the block of the looping construct.

Continue: This statement is used to skip the current iteration of the loop and continue to execute the next iteration until the looping construct is exited.

18. What are some of the popular frameworks in PHP?

There are many frameworks in PHP that are known for their usage. Following are some of them:

  • CodeIgniter
  • CakePHP
  • Laravel
  • Zend
  • Phalcon
  • Yii 2

19. What is the use of the final class and the final method in PHP?

The ‘final’ keyword, if present in a declaration, denotes that the current method does not support overriding by other classes. This is used when there is a requirement to create an immutable class.

Note: Properties cannot be declared as final. It is only methods and classes that get to be final.

20. How does JavaScript interact with PHP?

JavaScript is a client-side programming language, while PHP is a server-side scripting language. PHP has the ability to generate JavaScript variables, and this can be executed easily in the browser, thereby making it possible to pass variables to PHP using a simple URL.

Intermediate Interview Questions

21. Does PHP interact with HTML?

Yes, HTML and PHP interaction is the core of what makes PHP what it is. PHP scripts have the ability to generate HTML mode and move around information very easily.

PHP is a server-side scripting language, while HTML is a client-side language. This interaction helps bridge the gaps and use the best of both languages.

22. What are the types of arrays supported by PHP?

There are three main types of arrays that are used in PHP.

  • Indexed arrays: These are arrays that contain numerical data. Data access and storage are linear.
  • Associative arrays: There are arrays that contain strings for indexing elements.
  • Multidimensional arrays: These are arrays that contain more than one index and dimension.

23. How does the ‘foreach’ loop work in PHP?

The foreach statement is a looping construct used in PHP to iterate and loop through the array data type. The working of foreach is simple; with every single pass of the value, elements get assigned a value and pointers are incremented. This process is repeated until the end of the array.

The following is the syntax for using the foreach statement in PHP:

foreach(array)
{
Code inside the loop;
}

24. Differentiate between require() and require_once() functions.

require()require_once()
The inclusion and evaluation of filesIncludes files if they are not included before
Preferred for files with fewer functionsPreferred when there are a lot of functions

25. What are the data types present in PHP?

PHP supports three types of data handling, and they are as shown in the following table:

Scalar Data TypesCompound Data TypesSpecial Data Types
  • Boolean
  • Integer
  • Float
  • String
  •  Array
  • Object
  • NULL
  • Resource

26. How can a text be printed using PHP?

A text can be output onto the working environment using the following methods:

  • Echo
  • Print

The following code denotes the usage of both:

<?php echo "Using echo";
print "Using print"; ?>

27. Is it possible to set infinite execution time in PHP?

Yes, it is possible to have an infinite execution time in PHP for a script by adding the set_time_limit(0) function to the beginning of a script.

This can also be executed in the php.ini file if not at the beginning of the script.

28. What is the use of constructors and destructors in PHP?

Constructors are used in PHP as they allow you to pass parameters when creating a new object easily. This is used to initialize the variables for the particular object in consideration.

Destructors are methods used to destroy an object. Both of these are special methods provided in PHP for you to perform complex procedures using a single step.

29. What are some of the top Content Management Systems (CMS) used in PHP?

There are many CMS that are used in PHP. The popular ones are as mentioned below:

  • WordPress
  • Joomla
  • Magneto
  • Drupal

30. How are comments used in PHP?

There are two ways to use comments in PHP. They are single-line comments and multi-line comments.

Single-line comments can be used using the conventional ‘#’ sign.

Example:

<?php
# This is a comment
echo "Single-line comment";
?>

Multi-line comments can be denoted using ‘/* */’ in PHP.

Example:

<?php
/*
This is
a
Multi-line
Comment
In PHP;
*/

echo "Multi-line comment";

?>

31. What is the most used method for hashing passwords in PHP?

The crypt() function is widely used for this functionality as it provides a large amount of hashing algorithms that can be used. These algorithms include md5, sha1 or sha256.

32. Differentiate between an indexed array and an associative array.

Indexed arrays have elements that contain a numerical index value.

Example: $color=array("red","green","blue");

Here, red is at index 0, green at 1, and blue at 2.

Associative arrays, on the other hand, hold elements with string indices as shown below:

Example: $salary=array("Jacob"=>"20000","John"=>"44000","Josh"=>"60000");

33. What is the difference between ASP.NET and PHP?

ASP.NETPHP
A programming frameworkA scripting language
Compiled and executedInterpreted mode of execution
Designed for use on WindowsPlatform independent

34. What are sessions and cookies in PHP?

Sessions are global variables that are stored on the server in the architecture. Every single session is tagged with a unique server ID that is later used to work with the storage and retrieval of values.

Cookies are entities used to identify unique users in the architecture. It is a small file that the server plants into the client system. This is done to get useful information from the client for the development of various aspects of the server.

35. Is typecasting supported in PHP?

Yes, typecasting is supported by PHP and can be done very easily. Following are the types that can be cast in PHP:

  • (int), (integer): Cast to integer
  • (bool), (boolean): Cast to boolean
  • (float), (double), (real): Cast to float
  • (string): Cast to string
  • (array): Cast to array
  • (object): Cast to object

36. Can a form be submitted in PHP without making use of a submit button?

Yes, a form can be submitted without the explicit use of a button. This is done by making use of the JavaScript submit() function easily.

37. Does PHP support variable length argument functions?

Yes, PHP supports the use of variable length argument functions. This simply means that you can pass any number of arguments to a function. The syntax simply involves using three dots before the argument name as shown in the following example:

<?php

function add(...$num) {

$sum = 0;

foreach ($num as $n) {

$sum += $n;

}

return $sum;

}

echo add(5, 6, 7, 8);

?>

Output: 26

38. What is the use of session_start() and session_destroy() functions?

In PHP, the session_start() function is used to start a new session. However, it can also resume an existing session if it is stopped. In this case, the return will be the current session if resumed.

Syntax:

session_start();

The session_destroy() function is mostly used to destroy all of the session variables as shown below:

<?php

session_start();

session_destroy();

?>

39. How can you open a file in PHP?

PHP supports file operations by providing users with a plethora of file-related functions.

In the case of opening a file, the fopen() function is used. This function can open a file or a URL as per requirement. It takes two arguments: $filename and $mode.

Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

40. What are the different types of PHP errors?

There are three main types of errors in PHP. They are as follows:

  • Notice: A notice is a non-critical error that is not displayed to the user.
  • Warning: A warning is an error that is displayed to the user while the script is running.
  • Fatal error: This is the most critical type of error. A fatal error will cause immediate termination of the script.

Advanced Interview Questions

41. How can you get the IP address of a client in PHP?

The IP address of a client, who is connected, can be obtained easily in PHP by making use of the following syntax:

$_SERVER["REMOTE_ADDR"];

42. What is the use of $message and $$message in PHP?

Both $message and $$message are variables in PHP. The difference lies in the name. While $message is a variable with a fixed name, $$message is a variable with a name that is actually stored in $message.

Consider the following example:

If $message consists of ‘var’, then $$message is nothing but ‘$var’.

43 Differentiate between GET and POST methods in PHP.

GET MethodPOST Method
The GET method can only send a maximum of 1024 characters simultaneouslyThere is no restriction on the data size
GET does not support sending binary dataPOST supports binary data as well as ASCII
QUERY_STRING env variable is used to access the data that is sentThe HTTP protocol and the header are used to push the data
The $_GET associative array is used to access the sent informationThe $_POST associative array is used to access the sent information here

44. What is the use of lambda functions in PHP?

Being an anonymous function, the lambda function is used to first store data into a variable and then to pass it as arguments for the usage in other methods or functions.

Consider the following example:

$input = array(2, 5, 10);
$output = array_filter($input, function ($x) { return $x > 2; });

The lambda function definition here:

function ($x) { return $x > 2; });

This is used further to store data into a variable, and then you can use it when required without the requirement of defining it again.

45. Differentiate between compile-time exception and runtime exception in PHP.

As the name suggests, if there is an occurrence of any sort of exception while the script is being compiled, it is called a compile-time exception. The FileNotFoundException is a good example of a compile-time exception.

An exception that interrupts the script while running is called a runtime exception. The ArrayIndexOutOfBoundException is an example of a runtime exception.

46. What is the meaning of type hinting in PHP?

Type hinting is used in PHP when there is a requirement to explicitly define the data type of an argument when passing it through a function.

When this function is first called, PHP will run a quick check to analyze the presence of all the data types that are specified. If it is different, then the runtime will stop as an exception will be raised.

47. How is a URL connected to PHP?

Any URL can be connected to PHP easily by making use of the library called cURL. This comes as a default library with the standard installation of PHP.

The term ‘cURL’ stands for client-side URL, allowing users to connect to a URL and pick up information from that page to display.

48. What are the steps to create a new database using MySQL and PHP?

There are four basic steps that are used to create a new MySQL database in PHP. They are as follows:

  • First, a connection is established to the MySQL server using the PHP script.
  • Second, the connection is validated. If the connection is successful, then you can write a sample query to verify.
  • Queries that create the database are input and later stored into a string variable.
  • Then, the created queries are executed one after the other.

49. How does string concatenation work in PHP?

String concatenation is done easily in PHP by making use of the dot(.) operator. Consider the following example:

<?php $string1="Welcome"; $string2="to Intellipaat"; echo $string1 . " " . $string2; ?>

Output: Welcome to Intellipaat

50. Do you have any certification to boost your candidature for this PHP Developer role?

With this question, the interviewer is trying to assess if you have any exposure to real-time projects and hands-on experience. This is usually provided by a good certification program, and this gives an impression to the interviewer that you are serious about the career path you are aspiring for. If you do have any relevant experience, make sure to explain about what you learned and implemented during the certification course.

51. Compare PHP and Java.

CriteriaPHPJava
Deployment areaServer-side scriptingGeneral-purpose programming
Language typeDynamically typedStatically typed
Providing a rich set of APIsNoYes

52. How can we encrypt a password using PHP?

The crypt () function is used to create one-way encryption. It takes one input string and one optional parameter. The function is defined as:

crypt (input_string, salt)

where input_string consists of the string that has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The format is as follows:

php code

53. Explain how to submit a form without a submit button.

A form can be posted or submitted without the button in the following ways:

  • On the OnClick event of a label in the form, a JavaScript function can be called to submit the form.
    Example:
document.form_name.submit()
  • Using a Hyperlink: On clicking the link, a JavaScript function can be called.

Example:

Q5 php IQA code

  • A form can be submitted in the following ways as well without using the submit button:
    • Submitting a form by clicking a link
    • Submitting a form by selecting an option from the drop-down box with the invocation of an onChange event
    • Using JavaScript:
document.form.submit();
  • Using header(“location:page.php”);

54. How can we increase the execution time of a PHP script?

  • The default time allowed for a PHP script to execute is 30 seconds mentioned in the php.ini file. The function used is set_time_limit(int sec). If the value passed is ‘0’, it takes unlimited time. It should be noted that if the default timer is set to 30 seconds and 20 seconds is specified in set_time_limit(), the script will run for 45 seconds.
  • This time can be increased by modifying max_execution_time in seconds. The time must be changed keeping the environment of the server. This is because modifying the execution time will affect all the sites hosted by the server.
  • The script execution time can be increased by:
    • Using the sleep() function in the PHP script
    • Using the set_time_limit() function

The default limit is 30 seconds. The time limit can be set to zero to impose no time limit

To know more about PHP, enroll in our Online PHP Training Course now!

55. What is Zend Engine?

Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into memory and compiled into Zend OPCodes.

These OPCodes are executed and the HTML generated is sent to the client.

The Zend Engine provides memory and resource management and other standard services for the PHP language. Its performance, reliability, and extensibility have played a significant role in PHP’s increasing popularity.

56. What library is used for PDF in PHP?

The PDF functions in PHP can create PDF files using PDFlib version 6. PDFlib offers an object-oriented API for PHP5 in addition to the function-oriented API for PHP4.
There is also the » Panda module.

FPDF is a PHP class, which allows generating PDF files with pure PHP (without using PDFlib). F from FPDF stands for Free: we may use it for any requirement and modify it to suit our needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

57. What are the new features introduced in PHP7?

  • Zend Engine 3 performance improvements and 64-bit integer support on Windows
  • Uniform variable syntax
  • AST-based compilation process
  • Added Closure::call()
  • Bitwise shift consistency across platforms
  • (Null coalesce) operator
  • Unicode codepoint escape syntax
  • Return type declarations
  • Scalar type (integer, float, string, and Boolean) declarations

58. What is htaccess? Why do we use it and where?

The .htaccess files are configuration files of Apache Server that provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory; the directives apply to that directory and all subdirectories thereof.

These .htaccess files are used to change the functionality and features of the Apache web server.

For instance:

  • The .htaccess file is used for URL rewrite.
  • It is used to make the site password-protected.
  • It can restrict some IP addresses so that on these restricted IP addresses, the site will not open.

59. What are magic methods?

Magic methods are member functions that are available to all the instances of a class. Magic methods always start with ‘__’, for example, __construct(). All magic methods need to be declared as public.

To use a method, it should be defined within the class or the program scope. Various magic methods used in PHP5 are:

  • __construct()
  • __destruct()
  • __set()
  • __get()
  • __call()
  • __toString()
  • __sleep()
  • __wakeup()
  • __isset()
  • __unset()
  • __autoload()
  • __clone()

60. What is meant by PEAR in PHP?

PEAR is an acronym for PHP Extension and Application Repository. The purpose of PEAR is to provide:

  • A structured library of open-sourced code for PHP users
  • A system for code distribution and package maintenance
  • A standard style for writing code in PHP
  • PHP Foundation Classes (PFC)
  • PHP Extension Community Library (PECL)
  • A website, mailing lists, and download mirrors to support the PHP/PEAR community

CTA

All Courses

61. Explain soundex() and metaphone().

The soundex() function calculates the soundex key of a string. A soundex key is a 4-character long alphanumeric string that represents the English pronunciation of a word. The soundex() function can be used for spelling applications.

<?php 
$str= “hello”;
Echo soundex($str);
?>

The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if it is pronounced by an English (native) person. This function can also be used for spelling applications.

<?php 
echo metaphone(“world”);
?>

62. What is Smarty?

Smarty is a template engine written in PHP. Typically, these templates will include variables—like {$variable}—and a range of logical and loop operators to allow adaptability within the templates.

63. What is Memcache?

Memcache is a technology that caches objects in memory such that a web application can get to them really fast. It is used by sites, such as Digg, Facebook, and NowPublic, and is widely recognized as an essential ingredient in scaling any LAMP.

64. How can we execute a PHP script using a command line?

We just have to run the PHP CLI (Command-line Interface) program and provide the PHP script file name as the command-line argument, for example, php myScript.php, assuming php as the command to invoke the CLI program.

We have to keep in mind that if our PHP script is written for the Web CGI interface, it may not execute properly in the command-line environment.

10 thoughts on “Top 64 PHP Interview Questions and Answers”

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories