Ask your Question

Write to us

Ask Question

PHP Interview Questions

Add Your PHP Question Download PDF
  • 1 Which is the latest version of PHP

     The latest stable version of PHP is 7.1.0 released at December 1, 2016 .

  • 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.16, released  on 14th  july 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:-
    <?php
    echo 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

    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 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

    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 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
    ?>

  • 57 What is output of this code:

    when the string is evaluated in numeric context it works like: if a string does not contain any of the character 'e', 'E,' and valid numeric value(int type), it will be evaluated as a integer otherwise will be a float.

    the value taken by the initial string portion. if it has valid numeric then that value will be taken otherwise value will be 0. This is the case here happening.

    <?php echo '8k' + 1; ?>

     OUTPUT : 9

     

    <?php echo 'k8' + 1; ?>

     OUTPUT : 1

     

    <?php echo 4 + "10.2 k"; ?>

     OUTPUT : 14.2

  • 58 What will be the output of following.

    function changevalue(&$y)
    {
    $y = $y + 5;
    }

    $num = 8;
    changevalue($num);
    echo $num;

     It would be : 13

    Reference will take the value and will add 5 to it.

  • 59 How to find first array elements which are missing in second array.

     <?php

    $array1 = array("a" => "green", "red", "blue", "red");

    $array2 = array("b" => "green", "yellow", "red");

    $result = array_diff($array1, $array2);

     

    print_r($result);

     ?>

  • 60 what is headers already sent error , why we encounter this and how it can be resolved?

    A web page is composed of two parts, the header and the body. An error is seen like something:

    Warning: Cannot modify header information – headers already sent by (output started at /home/usr1/public_html/sent.php:42) in /home/usr1/public_html/includes/theme-header.php on line 12

    Header is generated automatically containing information related to server, cookies. Sometimes programmers want to change some of the header values. For example, if the PHP if generating XML output, the Content-Type should be changed to reflect this. Another common example is in redirecting the user’s browser to a different web page using the Location header element.

     The header must come first in the response from a web server and is separated from the body by one blank line. The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value. Because PHP simplifies many things for you, the problem may be hiding in plain site. Here are some guidelines for finding the problem:

     

    1) Find the header () statement that is causing the problem. The error must be at or before this line.

     

    2) Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.

     

    3) Make sure there is no white space outside of the PHP  start and end tags. While a blank line before the <?php start tag may look innocent, when processed by PHP, it will turn into an echo statement printing out a blank line.

     

     

  • 61 Why we use extract() in PHP ?

     The extract() function imports variables into the local symbol table from an array.

     
    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.
     
    Syntax:  extract(array,extract_rules,prefix)
     
    E.g. :
    <?php
     
    $varArray = array("course1" => "PHP", "course2"  => "JAVA","course3" => "HTML");
                                    
    extract($varArray);
     
    echo "$course1, $course2, $course3";
     
    ?>
  • 62 What will be the output ?

    $num =10;

    function multiply()
    { $num =$num *10; }
    multiply();
    echo $num;

     Output is 10

  • 63 Why we use list() function in PHP ?

     List() function is used to assign values to a list of variable in one operation and list only works on numerical arrays.

    <?php

    $varArray = array("PHP","MYsql","Jquery");

    list($a, $b, $c) = $varArray;

    echo  "I have knowledge of $a,$b and $c.";  

    ?>

    OUTPUT : I have knowledge of PHP,MYsql and Jquery.

  • 64 What is use of $this in PHP Classes

    $this is called pseudo variable and this is availabel when a method is called from within an Object context.

    $this is refrence to the calling object of the current class. When we need to call a method of a class 
    within the same class instead of creating object of that class we can use $this to call the method of the existing class.
     
    <?php
     
    Class A
    {
      public function getName()
      {
        $name = '';
        return $name;
      }

      public function getUserDetails()
      {
        $this->getName();              // to call the other method of the class we can use this operator.
       
      }

    }

      $obj = new A();
      echo $obj->getUserDetails();
     
    ?>
  • 65 What is PHP sessions default timeout.

     The default session timeout is 24 minutes (1440 seconds),

    however we can change this value by setting session.gc_maxlifetime() in php ini file.
  • 66 What is autoloading classes in PHP

     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

    e.g : 

    <?php

    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 .

     
  • 67 How to refresh a page using HTML

     To refresh the page using HTML we can use META 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">
    </head>
     
    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.html">
    </head>
     
    From the above code the page will refresh after 15 seconds, and   new URL will be target.html
  • 68 How would you find the number of repeated characters in a given string "abcabcxyz"

    Here we are giving the search string in a variable and in substr() function we will provide the length of the string we are searching for. we can search for a single character also and editing the length to one in substr() function.

     

     <?php  

        $text="abcabcxyz";  
        $search_char="abc";  
        $count="0";  
        for($x="0"; $x< strlen($text); $x++)  
          {   
            if(substr($text,$x,3)==$search_char)  
            {  
            $count=$count+1;  
             }  
          }  
        echo "count of string is". $count;  
     
        ?> 
  • 69 How would you separate numbers and character from a given string "68vfdksh90930hkjnvkj93890" .

    Here we are using preg_replace() function .

     <?php

    $string       =   "68vfdksh90930hkjnvkj93890";
    $numbers =   preg_replace('/[^0-9]/', '', $string);
    $chars       =   preg_replace(/[^a-zA-Z]/', '', $string);
     
    echo  'Numbers are :'. $numbers;
    echo '<br/>';
    echo   'Charcaters are:'.$chars;
     
    ?>
  • 70 How to get the extesnion of a file in PHP

     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);
  • 71 What is difference between var_dump and print_r

     var_dump function displays structured information about variables including its type,size and value

    e.g:

    <?php

    $colors=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

    var_dump($colors);

    ?>

    OUTPUT

    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 readbale format.

    Array will be presented in a format of key value

    e.g:

    <?php

    $colors=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

    print_r($colors);

    ?>

    OUTPUT

    Array ( [a] => red [b] => green [c] => blue [d] => yellow )

     

  • 72 What is the output?

    $x=array("aaa","ttt","www","ttt","yyy","tttt");
    $y=array_count_values($x);
    echo $y['ttt'];

     OUTPUT:

    3

  • 73 In PHP langauge is variables are case sensitive?

     Yes.

  • 74 What will be the output
    $years = 5;
    echo 'I have $years of experience in PHP';

     I have $years of experience in PHP

  • 75 What is the output?
    echo strspn('abcdefghi','abc');

     OUTPUT: 3

    STRSPN returns the number of matches found in the string.

  • 76 What is the output?

    $a = array(1,2,3=>4);
    $b = array(5,6,7);
    $c= array_combine($a,$b);
    print_r($c);

     OUTPUT:

    Array ( [1] => 5 [2] => 6 [4] => 7 ) 

  • 77 What is the output?

    $a1=array("a"=>"red","green","blue","yellow");
    $a2=array("e"=>"red","green","blue");
    $diffr = array_diff($a1,$a2);
    print_r($diffr);

     OUTPUT:

    Array ( [2] => yellow )

  • 78 What is the output?

    $string1="devloper@letsknowit.com";
    $newstring=strchr($string1,"@",true);
    echo $newstring;

     OUTPUT:

    devloper

  • 79 what will be output of following?$a=024;echo $a/4;

    5

    PHP will consider 024 as octal number which is equivalent to decimal 20