Skip to main content

PHP Interview Questions


1. Which is the latest version of PHP.
 The latest stable version of PHP is 5.6.7 released at March 20, 2015 .
2. Define PHP.
PHP is an open source server side scripting language used to develop dynamic websites . PHP  stands for Hypertext Preprocessor , also stood for  Personal Home Page . Now the implementations of PHP is produced by The PHP group .It was created by Rasmus lerdorf in 1995 . It is a free software released under the PHP license .
3. Who is the father of PHP.
Rasmus Lerdorf known as the father of PHP . Php was created by Rasmus Lerdorf In 1995 .
4. What is the current version of Apache.
The latest  stable version of  Apache  is  2.4.12, released  on 29th  January  2015.
5. What is difference between unset and unlink..
Unset is used to delete(destroy) a variable whereas unlink used to delete a file.
6. What is the difference between array_merge and array_combine.
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 .

<?php
$array1 = array("course1" => "java","course2" => "sql");
$array2 = array(("course1" => "php","course3" => "html");
$result = array_merge($array1, $array2);
print_r($result);
?>
OUTPUT : 
array
(
[course1] => php
[course2] => sql
[course3] => html
)

Array_combine creates a new array by using the key of one array as keys and using the value of other array as values.
<?php
$array1    = array("course1","course2");
$array2    = array(("php","html");
$new_array = array_combine($array1, $array2);
print_r($new_array);
?>
OUTPUT :
array
(
[course1]  => php
[course2]    => html
)
7. What is the difference between session and cookies.
There are some difference between session and cookies thath are as following:-

1 : Session are temporary and Cookies are parmanent.

2 : Session data is store on server while Cookies are store on user's computer.

3 :Cookies contents can be easily modify but to modify Session contents is very hard.

4 :Cookies could be save for future reference but Session couldn't when user close the browser Session data also lost.
8. How we declare cookies and how we expire it.
setcookie() function is used to set cookies in php.
To declare Cookies syntax will be:-    setcookie(name, value, expire, path, domain);
name    : Name of the cookie
value     : Value of the cookie
expire   : The time for cookie to expire
path      : path to save the cookie where we want to save the cookie information
domain : domain name on which we want to save the cookie
     
e.g    :  setcookie("username","harry",time()+60*60*60*24);
In the above example the cookie name is username having value harry and set for one day .
To expire cookies we have set the time of cookie in past
To expire Cookies syntax will be:     setcookie(name,value,time-3600);
9. What is use of var_dump .
var_dump() function is used to display structured information(type and value) about one or more variable.
syntax:- var_dump(variable1,variable2,.....variablen);
e.g    <?php
          $a=3.1;
          $b=true;
          var_dump($a,$b);
         ?>
output   :  float(3.1)
              bool(true)
10. What is str_replace().
This function replace some characters with some other characters in a string , this function is case sensitive.
syntax:- str_replace(find,replace,string);

find:-required,specifies the value to find.
replace:-required,specifies the value to replace the value in find.
string:-required,specifies the string to searched.

for examlpe:- 
<?phpecho str_replace("world","india","hello world");
?>
output:-     hello india
11. What is the difference between include() and require().
include() function gives the warning when specified file not found but all script will be continually  executed.
e.g.
    <?php
                  include("filename.php");
                  echo "hello";
              ?>
output:- hello
In the above  example if file not found then it gives warning and print the hello because warning does not  stop script and echo will be execute.
require() function gives the fatal error when specifies file is not found and stop the script. 
e.g.    <?php

                require("filename.php");
                echo "hello";
           ?>
output:-   it gives fatal error and stop the script ,echo will not be executed.
12. What is final class.
final class is a class that can not be inherited.Its protect the methods of class to be overriden by the child classes.
e.g.    final class baseclass
            {
                public function mymethod()  {
                          echo  "baseclass method";
                            }

            }

            class derivedclass extends baseclass
             {
                        public function mymethod() {
                                 echo   "derivedclass method";

                              }

               }

          $c= new derivedclass();
          $c->mymethod();

  In the above example base class is declared as final and hence can not be inherited.
 derived class tries to extends baseclass then compile error will be generated.
13. What is difference between abstract class and interface classes.
Interface : An interface does not contain any code,it contain only declaration of    methods,properties,events. Interfaces allow us to code which specifies which methods a class must have implement . Interfaces defines with the word interface . All methods in interfaces must be public
           e.g :     interface myItem

                    {

                        void Id();
                       string description();
                        string Runtest(int testnumber);

                    }

 Abstract class : Abstract classes are look like interfaces.Abstract classes may contain code although it may also have abstract method that do not have code. Abstract classes defines only signature of the method ,not implementation.  The child class which inherit the abstarct class must define all the abstarct methods of its parent class .

         e.g        abstract class myItem

                    {

                        abstract protected function getitem();
                        abstract protected function setitem();

                    }
14. What is difference between echo() and print().
echo() and print() function both are used to show the output on the visitors screen but in echo we can take  one or more parameters.

 print() has a return value of true or false whereas echo has a void return type.

 echo() is slightly faster than print.
15. What is the difference between PHP4 and PHP5.
There are some difference between PHP4 and PHP5 that are as following:-

      1) In PHP5 abstract classes are used but not used in PHP4.

      2) In PHP5 interfaces are used but not used in PHP4.

      3) In PHP5 visibility are used but not used in PHP4.

      4) In PHP5 magic methods are used but not uesd in PHP4.

      5) In PHP5 typehinting are used but not used in PHP4.

      6) In PHP5 cloning are used but not used in PHP4.

      7) In PHP5 construtor are written as __construct keyword but in PHP4 are written as class name.
16. How many types of errors in PHP.
There are mainly three types of error in php. These are -

       (1) Notice error

       (2) Warning error

       (3) Fatal error

 Notice error happened when a variable not decleared but it is used.

Warning error occurred when a package not defined and some functionality has been used in the program.These are not serious errors,       they continue the execution of script.

 And Fatal error are those errors when an object call a class and the class not present there.These errors are serious     error  which can stop the execution of script
17. Why do we use ob_start().
Ob_start used to active the output buffering .When output buffering is on all output of the page sent at one time to the browser ,otherwise sometimes we face headers already sent type errors.
18. What is a .htacces file.
.htaccess is a configuration file running on Apache server.These .htaccess file used to change the functionality and features of apache web  server .

 e.g   .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 adresses  site will not open.
19. Is PHP an interpreted language or compiler language.
PHP is an interpreted language.
20. What is the difference between compiler language and interpreted language.
 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.
 
21. What are web services in PHP.
Web services converts our applicaton into a web-application ,which can publish its functions and messages to the internet users.The main web services platform is XML and HTTP.Web services can be published ,found and used through web.
22. What is static methods and properties in PHP.
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 overcome   long overhead of instantiation of classes .
  e.g 
  <?php

      Class foo
      {
        public static  $variable_name = 'it is a static variable';
      }
      echo foo :: $variable_name;      // Output  :  it is a static varaible   

  ?>
23. What is static methods and properties in PHP.
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 overcome   long overhead of instantiation of classes .
  e.g 
<?php

  Class foo
  {
  public static  $variable_name = 'it is a static variable';
   }
    echo foo :: $variable_name;      // Output  :  it is a static varaible  
?>
24. What is type hinting in PHP.
Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an error will occur.PHP 5 introduces type hinting  and the functions are able to  force the parameters to be objects, interfaces ,array .
25. Is multiple inheritance supported in PHP.
No, multiple inheritance is not supported by PHP
26. How can we define constants in PHP.
In PHP we can define constants with the keyword define .

e.g :
<?PHP
define(‘SiteName’,’Letsknowit.com’);

 echo  ‘You are visiting’ .Sitename;
?>

OUTPUT :  You are visiting Letsknowit.com
 
27. How can we change the time zones using PHP.
We can change the time zones by using  date_default_timezone_set() function.
e.g :

<?php

         date_default_timezone_set('America/Los_Angeles');

?>
28. How to read the contents of a file in PHP.
<?php
   $fileName = 'instructions.txt';
   $file = fopen(“instructions.txt”,”r”)  or exit(“Unable to open the file!”) ;
   While( ! feof($file) )                            // feof()checks the end of  file in php
  {
       echo   fgets($file);                       // fgets() read a  fileline by line in php
  }
  fclose($file);                                      // fclose() used to close a file  in php
?>
29. How to read a file character by character.
<?php
fgetc() function is used to read a file character by character.
e.g.
   While(!feof($file))                            // feof()checks the end of  file in php
   {
       echo   fgetc($file);                        // fgetc() read a  file character  by character in PHP
   }
?>
30. Define PHP filter.
PHP filter is used to validate the data coming from different sources like the user’s input.
It is important part of a web application to test, validate the data coming from insecure sources.
We have different functions to validate the data:

filter_var();
filter_var_array()
filter input();
filter_input_array();
31.  Which function is used to remove HTML tags from data.
Strip_tags() function is used to remove html tags.
 e.g :
<?php
               $data            =   '<p>Web Development</p>' ;

              echo  $profession =  strip_tags($data);           //  It will remove the <p> tag from output.
?>
 
32. Why we use func_num_args() function in PHP.
func_num_args () used to get the number of arguments passed to the  function .
e.g :
<?php
function students()
  {
   $no_of_arguments          =  func_num_args();
    echo  "No Of Arguments = $no_of_arguments”;
   }
  student($name , $age ,$address);    // function call
?>
OUTPUT  : No Of Arguments = 3
 
33. Why we use nl2br().
nl2br  inserts HTML line breaks(<br/>)  before all new lines in a string .
e.g :
<?php
   echo  nl2br(“Thanks for visiting letsknowit.com /n see you soon .”);
?>
 OUTPUT : Thanks for visiting letsknowit.com  <br/>
                    See you soon .
34. What is ajax and how it is useful to us.
Ajax  is termed as Asynchronus javascript and XML .It is used for creating fast and dynamic web pages.With ajax it is possible to be update part of web page asynchronously (in the background) without refreshing the whole page.It is used on client side to create asynchronus web appliation
35.  What is differnce between HTML and XHTML.
1 : HTML stands for HyperText Markup Language and an application of SGML(Standard Gneralized Markup Language ).
    Whereas XHTML (Extensible Hyper text Markup Language) is an application of XML .

2 :HTML permit the omission of certain tags and use attribute minimization whereas XHTML does not permit the omission of any tag .A XML document must be well formed ,means there must be an end tag for every start tag.
36. What is the reason behind selecting LAMP for web development.
The main reason behind selecting LAMP  is :
All are open sources and free to use.
The security of LINUX is much more than windows operating system.
The Apache server have better security and functionality compared to Apache .
MySql is a world  wide  open source database and enrich in functionality and security .
 PHP is an open source and free to use.It is faster than any other scripting languages
37. How to execute PHP through command line Interface.
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 .
e.g :
php  index.php
38. What are magic methods in PHP..
Magic methods are very easy to identify, that every magical method name is started with double underscore( __)sign. We can not declare any user-defined functions with __ sign.

Some magic methods are :

__construct() , __destruct()  ,    __call()   ,  __callStatic()  ,  __get(),  __set()     , __isset()     ,__unset()
,  __sleep()       ,  __wakeup(),   __toString()  , __invoke()    , __set_state() ,  __clone().
39. What is the difference between GET and POST methods.
 GET Method:

  1) All the name value pairs are submitted as a query string in URL.

  2) It's not secured.

  3) Length of the string is restricted about 256.

  4) If method is not mentioned in the Form tag, this is the default method used.

  5) Data is always submitted in the form of text.


 POST Method:

  1) All the name value pairs are submitted in the Message Body of the request.

  2) Length of the string (amount of data submitted) is not restricted.

  3) Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser.

  4) If post method is used and if the page is refreshed it would prompt before the request is resubmitted.

  5) 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.
 
40. What are access control modifiers in php.
Keywords public,protected and private are the three types of access control modifiers in php.With  the help of these  keywords we can manage  the accessing  of a method or property of a class  in php
41. What is difference between public, private and protected in php.
Public :    
The items which are declared public can be access from everywhere ie access from inside the class ,access in inherited class and   access from outside the class.

Protected :
The items which are declared protected can be access inside the class that defines the item  and can acess in its child classes  (ie access in its inherited class) .

Private :
The items which are declared private can only be access inside its class that defines the item.
42. How can we get all the properties of browser in PHP.
We can get the browser properties in PHP by :
<?php
$_SERVER ['HTTP_USER_AGENT'] ;
?>
43. How to get difference between two dates.
$firstdate               = "2010-10-07";
$seconddate        = "2014-03-10";

$differnce              = abs(strtotime($date2) - strtotime($date1));

$years                   =   floor($differnce / (365*60*60*24));
$months               =   floor(($differnce - $years * 365*60*60*24) / (30*60*60*24));
$days                    =   floor(($differnce- $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d daysn", $years, $months, $days);
44. How to get the names of all included and required files for a particular page in PHP.
The function get_included_files ()  function 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
45. What is end function in PHP.
End function can set the pointer of an array to the last element of array.
e.g : 
<?php
$arr               =  array('name'=>'angel' ,'city'=>'delhi' ,'profession'=>'web developer');                               
$lastValue     = end($arr);
?>
OUTPUT :  web developer
46. How to get the number of elements in an array.
We have two functions to get the number of elements in an array ie count() and sizeof().
Synatx : count ($array_name) and sizeof($array_name)
47. Why we use strpos in PHP.
Strpos 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.
Synatx : strpos(‘stringtosearchin’ ,’stringtosearch’);
e.g  :
<?php
         $mystring   =  ’lets knowit ’;
         $find            =  ‘knowit ’;
         $result        =  strpos($mystring,$find)     //OUTPUT : 6
?>
48. How can we destroy a session in PHP.
We can destroy session by:
<?php
 session_destroy() ;
 ?>
To delete a specific session variable we use
<?php
 session_unset($_SESSION['variable_name']) ;
?>

49. What is the syntax to send a mail in PHP.
In PHP mail () function is used to send mails.

Syntax:
 mail (to , subject ,message ,headers, parameters);

50. What is ternary operator in PHP.
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.
e.g
<?php
$decision = ($age >18) ? 'can vote’ : 'can not vote' ;
?>


By using if statement we can write the above code as :
 
<?php
If($age>18){
$decision = 'can vote';
}
else{
$decision = 'can not  vote';
 }
?>

51. How many types of ready states in ajax.
There are 5ready state in ajax. these are :

  ready state 0: request not initialized

  ready state 1: server connection established

  ready state 2: request received

   ready state 3: processing request

  ready state 4: request finished and response is ready
52. Why we use array_flip.
array_flip exchange the keys with their associated values in array ie. Keys becomes values and values becomes keys.

<?php
$arrayName    = array("course1"=>"php","course2"=>"html");

$new_array    =  array_flip($arrayName);
print_r($new_array);
?>
OUTPUT :

Array
(
[php]     => course1

[html]    => course2)
53. What is difference between single quotes and double quotes in php.
 When string is in single quotes php will not evaluate it . If there is a string with single quotes and if we place a variable in that it would not substitute its value in string,  whereas double quotes support variable expansion. If we place variable in double quotes it would substitute its value in string.

 <?php

                  $str = 1;
                  echo  '$str is a value';       // OUTPUT  : $str is a value
                  echo  "$str is a value";       //OUTPUT   : 1 is a value

 ?>
54. How can we resolve maximum allocation time exceeds error.
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 page to increase the execution time.

And to  change memory_limit write ini_set(‘memory_limit  ,128M )

3. From .htaccess file we ncrease time and memory  by

 <IfModule mod_php5>

php_value max_execution_time 360

php_value m emory_limit  128M

</ IfModule >
55. How can we get the first element of an array in php.
We can get the first element of an array by the function current();

<?php

$arr                =  array('name'=>'angel','age'=>'23','city'=>'delhi','profession'=>'php developer');
$firstvalue     =  current($arr);

?>

 OUTPUT :  angel
56. What is difference between strstr and stristr..
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.

e.g :
<?php
$email = me@letsknowit.com
$result  =  strstr($email , ‘@’);    //output : @letsknowit.com
?>

Comments