PHP Interview Questions :
In this section I am going to provide some frequently asked PHP Interview Questions which will help you to clear interview session easily.

  • PHP is a recursive acronym for "PHP: Hypertext Preprocessor" and was earlier known as Personal Home Page.
  • PHP is a server side scripting language used to develop dynamic websites.
  • It was introduced in 1993 by Rasmus Lerdorf.
  • It runs on Zend Engine 3.0 and latest version of PHP is PHP7.0
  • It is written in Perl and C.
  • In PHP we don't have to use data types with variables.
  • In PHP we require source code to execute the program while in other programming languages we don't require source code as we compile the source code and convert into exe or war file and that file we can execute it.
All PHP code must be included inside one of the three special markup tags that are recognised by the PHP Parser.

// First way and most commonly preferred

// PHP code goes here


// Second way also known as short tags

// PHP code goes here


// Third way
<script language="php">

// PHP code goes here


  • PHP echo and print both are PHP Statement.
  • Both are used to display the output in PHP..


  1. echo is a statement i.e used to display the output. It can be used with parentheses echo or without parentheses echo.
  2. echo can pass multiple string separated as ( , )
  3. echo is marginally faster then print since it does not return any value


  1. print is also a statement i.e used to display the output. It can be used with parentheses print( ) or without parentheses print.
  2. Using print we can't pass multiple argument
  3. print always return 1
  • var_dump function displays structured information about one or more variables including its type, size and value.
  • Syntax:- var_dump(variable1,variable2,.....variablen);
  • Interpreted language executes line by line, if there is some error on a line it stops the execution of script.
  • Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script, if there is some error on some line.
  • PHP is a interpreted language.
  • The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

  • The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
  • Parameter : is a variable in a method definition.

  • Arguments : When we call a method, the arguments are the data we pass into the methods parameters.
There are mainly four types of error in php. These are -
  1. Parse error : The parse error occurs if there is a syntax mistake in the script; the output is Parse error. A parse error stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The common reasons for parse errors are as follows:
    • Unclosed quotes
    • Missing or Extra parentheses
    • Unclosed braces
    • Missing semicolon

  2. Notice error : These are small, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although the default behaviour can be changed.

  3. Warning error : Warnings are more severe errors like attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

  4. Fatal error : These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
  • .htaccess is a configuration file running on Apache server.These .htaccess file used to change the functionality and features of apache web server .

  • Example :
  • .htaccess file used for url rewrite.
  • .htaccess file used to make the site password protected.
  • .htaccess file can restrict some ip addresses ,so that on restricted ip addresses site will not open.
    GET Method:
  • All the name value pairs are submitted as a query string in URL.
  • It's not secured.
  • Length of the string is restricted about 256.
  • If method is not mentioned in the Form tag, this is the default method used.
  • Data is always submitted in the form of text.

  • POST Method:
  • All the name value pairs are submitted in the Message Body of the request.
  • Length of the string (amount of data submitted) is not restricted.
  • Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser.
  • If post method is used and if the page is refreshed it would prompt before the request is resubmitted.
  • If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
  • The ternary operator is a short form of doing if statement. We called it ternary operator because it takes three operands ie. 1– condition, 2- result for true, 3– result for false.
Example :

                                            $decision = ($age>18) ? 'can vote' : 'can not vote' ;

By using if statement we can write the above code as :

                                            if($age>18) {

                                            $decision = 'can vote';

                                            } else {

                                            $decision = 'can not vote';


  • We can resolve these errors through php.ini file or through .htaccess file.
    1. From php.ini file increase the max_execution_time = 360 (or more according to need) and change memory_limit = 128M (or more according to need).
    2. From php file we can increase time by writing ini_set( 'max_execution_time', 360 ) at top of php file to increase the execution time and to change memory_limit write ini_set( 'memory_limit', 128M ).
    3. From .htaccess file we increase time and memory by -
    4.                                             <IfModule mod_php5>
                                                      php_value max_execution_time 360
                                                      php_value memory_limit 128M
                                                  </IfModule >
  • To refresh the page using HTML we can use META tag to refresh the page or to redirect to other page after certain period of time.

  • To refresh the page we can use:
  •                                             <head>
                                                <meta http-equiv="refresh" content="15">
  • Then the page will refresh after every 15 seconds.

  • To redirect to other url we can use below code.
  •                                             <head>
                                                <meta http-equiv="refresh" content="15" URL="target.php">
  • From the above code the page will refresh after 15 seconds, and new URL will be target.php
  • var_dump function displays structured information about variables including its type, size and value.

  • Example :
                                                $colors = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
                                                array(4) { ["a"]=> string(3) "red" ["b"]=> string(5) "green" ["c"]=> string(4) "blue" ["d"]=> string(6) "yellow" }
  • print_r() displays information about a variable in a human readable format.
  • Array will be presented in a format of key value.

  • Example :
                                                $colors = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
                                                Array ( [a] => red [b] => green [c] => blue [d] => yellow )
Memcache is a cache mechanism that caches objects in memory such that your web application can get to them really fast. It is widely recognized as an essential ingredient in scaling any LAMP.
  • For finding length of string we use strlen() function.
  • For array we use count() function and also we can use sizeof() function to get number of elements in an array.
  • We cannot change the value of a constant.
  • To define a constant we have to use define() function and to retrieve the value of a constant, we have to simply specifying its name.

  • Example :
                                                define("MINSIZE", 50);
                                                echo MINSIZE;
                                                // we can also use constant function to retrieve value of constant.
                                                echo constant("MINSIZE");
Magic Constants:
Magic Constants are written in uppercase letters and prefixed and suffixed with two underscores.
  1. __LINE__ : to get line no in which the constant is used.
  2. __CLASS__ : to get class name in which the constant is used.
  3. __FILE__ : to get the full path or file name in which constant is used.
  4. __METHOD__ : to get the name of method in which constant is used.
Numeric Array : An array with a numeric index. Values are stored and accessed in linear fashion.
Associative Array : Associative arrays are arrays that use named keys that you assign to them.
Example :

                                            $capitals = array("India"=>"New Delhi", "China"=>"Beijing", "Srilanka"=>"Colombo");

Multidimensional Array : An array containing one or more arrays and values are accessed using multiple indices.
$message is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.
  • $message is a variable and $$message is a variable of another variable.
  • $$message allows the developer to change the name of the variable dynamically.

  • Example :
                                                $name = "katrina";
                                                $katrina = "Salman";
                                                echo $name //Output:- katrina
                                                echo $$name //Output:- Salman
  • unset() is used to destroy a variable where as unlink() is used to destroy or delete a file.
    • array_merge() merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings key then the later value overrides the previous value for that key.

    • array_combine() creates a new array by using the key of one array as keys and using the value of other array as values.
    func_num_args () used to get the number of arguments passed to the function .
    Example :
                                                function students()
                                                $no_of_arguments = func_num_args();
                                                echo  "No Of Arguments = $no_of_arguments";
                                                student($name, $age, $address);    // function call
                                                No Of Arguments = 3
  • The function get_included_files() is used to get the names of all required and included files in a page.
  • It returns an array with the names of included and required files in a page.
  • array_flip() function exchange the keys with their associated values in array i.e. Keys becomes values and values becomes keys.
                                                $arrayName = array("course1"=>"php", "course2"=>"html");
                                                $new_array =  array_flip($arrayName);
                                                Output :
                                                [php] => course1,
                                                [html] => course2
  • We can get the browser properties in PHP by $_SERVER['HTTP_USER_AGENT']
  • Yes, we can use the urlencode() function to be able to protect special characters.
  • The use of the set_time_limit(int seconds) enables us to extend the execution time of a php script.
  • The default limit is 30 seconds.
  • strip_tags() function is used to remove html tags.
    Example :
                                                $data = '<p>Web Development</p>';
                                                echo $profession = strip_tags($data);
                                                    //  It will remove the <p> tag from output.
    nl2br inserts HTML line breaks(<br/>) before all new lines in a string .
    Example :
                                                echo nl2br("Thanks for visiting /n See you soon .");
                                                Output : Thanks for visiting  
    See you soon . */ ?>
  • AJAX is termed as Asynchronous Javascript and XML.
  • It is used for creating fast and dynamic web pages.
  • With AJAX it is possible to update part of web page asynchronously (in the background) without refreshing the complete page.
  • It is used on client side to create asynchronous web application.
  • In CLI we have to provide the script file name started with PHP tag as a command line argument and it runs after press enter.
    Example :
                                                /usr/bin/php  index.php
  • extract function uses array keys as variable names and array values as variable values.
  • For each element of array it will create a variable in the current symbol table.

  • Example :
                                                $varArray = array("course1" => "PHP", "course2" => "JAVA", "course3" => "HTML");
                                                echo "$course1, $course2, $course3";
    The default session timeout is 24 minutes (1440 seconds), however we can change this value by setting session.gc_maxlifetime() in php.ini file.
    • We can get a file extension in following ways:
    1.                                             $filename = $_FILES['image']['name'];
                                                  $ext =  pathinfo($filename, PATHINFO_EXTENSION);
    2.                                              $filename = $_FILES['image']['name'];
                                                  $array = explode('.', $filename);
                                                  $ext = end($array);
    • SOAP stands for Simple Object Access Protocol and REST stands for Representation State Transfer.
    • SOAP is a protocol and REST is an architectural style.
    • SOAP permits XML data format only but REST permits different data format such as Plain text, HTML, XML, JSON etc.
    • SOAP defines standards to be strictly followed but REST doesn't define to much standards like SOAP.
    • SOAP uses WSDL (Web Service Definition Language) for describing the functionality offered by a web service and REST uses WADL (Web Application Description Language) for describing the functionality offered by a web service.
    • SOAP requests send using HTTP POST method because SOAP request is formally big and can not not be send in query string, REST requests can send using both HTTP GET and POST and due to which GET request can be cached here.
    • SOAP requires more bandwidth and resource than REST so avoid to use SOAP where bandwidth is very limited.
    • SOAP can't use REST because it is a protocol but REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP
    • SOAP is less preferred than REST.
    To concatenate two string variables together, use the dot (.) operator.
    PHP provides a function getenv() to access the value of all the environment variables.
    call_user_func() function is for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.
  • call_user_func('functionName', 'argument1', 'argument2')
  • You can also use call_user_func_array('functionName', array('array','of','arguments')).
  •                                                 <?php
                                                call_user_func(function() { echo 'anonymous function called.'; });
                                                    // Output: anonymous function called
                                                    function barber($type)
                                                    echo "You wanted a $type haircut, no problem\n";
                                                    call_user_func('barber', "mushroom"); // You wanted a mushroom haircut, no problem
                                                    call_user_func('barber', "shave"); // You wanted a shave haircut, no problem
                                                    barber('mushroom'); // You wanted a mushroom haircut, no problem
                                                    barber('shave'); // You wanted a shave haircut, no problem
  • The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location.
  • The redirection script should be at the very top of the page to prevent any other part of the page from loading.
  • The target is specified by the Location: header as the argument to the header() function.
  • After calling this function the exit() function can be used to halt parsing of rest of the code.
  • The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
  • The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
  • PHP provided setcookie() function to set a cookie.
  • This function requires up to six arguments and should be called before <html> tag.
  • For each cookie this function has to be called separately.
  • Syntax: setcookie(name, value, expire, path, domain, security);
  • PHP provides many ways to access cookies.
  • Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables.
  • We can use isset() function to check if a cookie is set or not.
    To delete a cookie we should call setcookie() with the name argument only.
  • A PHP session is easily started by making a call to the session_start() function.
  • This function first checks if a session is already started and if none is started then it starts one.
  • It is recommended to put the call to session_start() at the beginning of the file.
  • Session variables are stored in associative array called $_SESSION[].
  • These variables can be accessed during lifetime of a session.
  • Make use of isset() function to check if session variable is already set or not.
    To unset a single variable use session_unset($_SESSION['variable_name']) function.
    A PHP session can be destroyed by session_destroy() function.
    $GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
    $_SERVER is an array including information created by the web server such as paths, headers, and script locations.
    $_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
  • We can get the first element of an array by using current() function.
  •                                             <?php
                                                $arr = array('name'=>'angel', 'age'=>'23', 'city'=>'delhi', 'profession'=>'php developer');
                                                $first_value = current($arr);
                                                Output :
    strstr and stristr both are used to search for the first occurrence of a string inside another string.
    Difference : the strstr() function is case sensitive and stristr() is case insensitive.
    Example :
                                                $email =
                                                $result  =  strstr($email , '@');
                                                // Output:
  • strpos() function used to find the first occurrence of a string in another string.
  • It return the position of the substring in a string.
  • If the searched string will not exists in the searching string it return false.
  • Syntax : strpos("stringtosearchin", "stringtosearch");
    Example :
                                                $mystring =  "lets knowit";
                                                $find  =  "knowit";
                                                $result = strpos($mystring, $find);
                                                // OUTPUT: 6
    end() function can set the pointer of an array to the last element of array. Example :
                                                $arr = array('name'=>'angel' ,'city'=>'delhi', 'profession'=>'web developer');
                                                $lastValue = end($arr);
                                                // Output : web developer
                                                $startTime= microtime(true);
                                                /** Write here you code to check **/
                                                /** Write here you code to check **/
                                                $endTime= microtime(true);
                                                echo 'Time Taken to execute the code:'.$endTime-$startTime
  • Register the variable into the session.
  • Pass the variable as a cookie.
  • Pass the variable as part of the URL.
  • crypt(), md5(), bcrypt() etc.
    move_uploaded_file( string filename, string destination)
    • Laravel
    • CakePHP
    • CodeIgniter
    • Yii 2
    • Symfony
    • Zend Framework
    • The main difference between session and cookie is that cookies are stored on user's computer in the text file format while sessions are stored on the server side.
    • Cookies can't hold multiple variables on the other hand Session can hold multiple variables.
    • You can manually set an expiry for a cookie, while session only remains active as long as browser is open
    • PHP provides various functions to read data from file.
    • There are different functions that allow you to read all file data, read data line by line and read data character by character.
    • PHP file read functions are given below:
      1. fread()
      2. fgets()
      3. fgetc()
    • PHP fwrite() and fputs() functions are used to write data into file.
    • To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.
    The readfile() function is used to download file in PHP.
    • The mail() function is used to send email in PHP.

    • Syntax: mail($to,$subject,$message,$header)
    • Check if "display_errors" is equal "on" in the php.ini or declare "ini_set('display_errors', 1)" in your script.
    • Then, include "error_reporting(E_ALL)" in your code to display all types of error messages during the script execution.

    • Enabling error messages is very important especially during the debugging process as you can instantly get the exact line that is producing the error and you can see also if the script in general is behaving correctly.
  • PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.
  • An example of a PSR is PSR-2, which is a coding style guide.
    • Composer is a tool for dependency management.
    • We are able to declare the libraries of our product relies on.
    • Composer will manage the installation and updating of the libraries.
    • The benefit is a consistent way of managing the libraries you depend on and you will spend less time managing the libraries you depend on in your project.
    • A persistent cookie is a cookie which is stored in a cookie file permanently on the browser.
    • A persistent cookie can be used for tracking long-term information.
    • Persistent cookies are less secure.
                                                $array = array('one','two');
                                                echo json_encode($array); //use json_decode for decode
    Add a token on every important request to secure important operations.
    By using php function htmlentities(), trim(), htmlspecialchars(), strip_tags() etc.
    By using mysql_real_escape_string() function.
    • sort() - sort arrays in ascending order.
    • rsort() - sort arrays in descending order.
    • asort() - sort associative arrays in ascending order, according to the value.
    • ksort() - sort associative arrays in ascending order, according to the key.
    • arsort() - sort associative arrays in descending order, according to the value.
    • krsort() - sort associative arrays in descending order, according to the key.
    • usort() - sort an array using a user-defined comparison function.
    • uksort() — sort an array by keys using a user-defined comparison function.

    Example : usort()
                                                function cmp($a, $b)
                                                if ($a == $b) {
                                                return 0;
                                                return ($a < $b) ? -1 : 1;
                                                $a = array(3, 2, 5, 6, 1);
                                                usort($a, "cmp");
                                                foreach ($a as $key => $value) {
                                                echo "$key: $value\n";
                                                    Output :
                                                    0: 1
                                                    1: 2
                                                    2: 3
                                                    3: 5
                                                    4: 6
    • Scalar type declarations
    • Return type declarations
    • Null coalescing operator (??)
    • Spaceship operator
    • Constant arrays using define()
    • Anonymous classes
    • Closure::call method
    • Group use declaration
    • Generator return expressions
    • Delegation
    PHP provides a special magic function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
    • Like constructor we can define a destructor function using function __destruct().
    • This will release all the resources with-in a destructor.
    Once we have defined the class, then we can create as many objects as we like of that class type.
    Below is an example of how to create object using new keyword.
    $obj1 = new Customer();
    $obj2 = new Customer();
    $obj3 = new Customer();
    • A static method is accessible without needing instantiation of a class.
    • It means there is no need to make an object to call the static methods.
    • static methods and properties can be directly call from its class name with (::) a scope resolution operator.
    • They cannot be call from the object of its class.
    • We need static methods to overcomelong overhead of instantiation of classes.

    Example :
          Class foo
            public static $variable_name = 'it is a static variable';
          echo foo :: $variable_name;
          // Output : it is a static varaible
    • Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an fatal error will occur.
    • PHP5 introduces type hinting and the functions are able to force the parameters to be objects, interfaces, array.
    • With autoloaders PHP is given a last chance to load the class or interface before it fails with an error.
    • spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are not defined.

    • Example :
      spl_autoload_register(function ($classname) {
          include  $classname . '.php';
      $object  = new Class1();
      $object2 = new Class2();
    • In the above example we do not need to include class1.php and class2.php .
    • spl_autoload_register() function will automatically load class1.php and class2.php .
    • We can also use __autoload() magic function but it is discouraged as it is going to be deprecated.
    No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.
    • Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported.
    • A Trait cannot be instantiated on its own.
    • CURL stand for Client URL.
    • CURL is a library to transfer data via various protocol like http, ftp, tftp etc.
    • By using CURL we can send HTTP request using various method like GET, POST etc.

    • Below are some general thing which we can do using PHP curl library:
    1. Downloading HTML from URL in our PHP Code.
    2. Sending POST request on any URL.
    3. Calling Rest full API.

    To use curl in PHP is very straightforward.
    1. Calling Rest full API.
    2. Initialize a curl session.
    3. Set various options for the session.
    4. Execute and fetch/send data from/to server.
    5. Close the session.
    • To get the data from website, we can make use of curl.
    In the below code, just update the CURLOPT_URL to which websites data you want to get.
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    $output = curl_exec($curl);
    echo $output;
    1. Initialize a curl session use curl_init().
    2. Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term "curl" using parameter "q=". Set option for CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
    3. Execute the curl session using curl_exec().
    4. Close the curl session we have created.
    5. Output the return string.
    $postData = array(
       "firstname" => "rahul",
       "lastname" => "yadav",
       "emailid" => ""
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    $output = curl_exec($curl);
    echo $output;
    • PSR - PHP Standard Recommendations
    • CURL - Client URL
    • PEAR - PHP Extensions and Application Repository
    • JSON - Javascript Object Notation
    • AJAX - Asynchronous Javasript and XML
    • SOAP - Simple Object Access Protocol
    • REST - Representational State Transfer
    • PEAR stands for PHP Extension and Application Repository.
    • The idea behind the Pear was to be able to reuse the existing code and packages, to promote a standard coding style throughout.
    • It also provided a way to install PECL(PHP Extension Community Library) extensions.
    • In many ways it is similar to 'Composer'(php's de facto package and dependency manager).
    • Composer downloads and installs packages from
    • Pear downloads packages from
    About Me
    Rahul Yadav

    Rahul Yadav

    Technical Architect

    Kuala Lumpur, Malaysia

    Connect Me:     

    I'm a Full Stack Web Developer working in a MNC and passionate of developing modern web and mobile applications.

    I have designed and developed CodephpOnline & CodephpOnline Wiki platform to expatiate my coding and technology learning experiences.

    In my leisure time, I write technical articles on web development such as PHP, Laravel, CodeIgniter, Mediawiki, Linux, Angular, Ionic, ReactJS, NodeJS, AJAX, jQuery, Cloud and more.

    Tag Cloud