All interview topics
Full-Stack, Web & Mobile

PHP Interview Questions and Answers

Practice PHP interview questions and answers organized by difficulty, with revealable explanations and related topics.

82 questionsEntry → Expert

Entry questions

7 questions
  1. Question 1
    Entry

    What are the keys & values in an indexed array?

    • PHP
    Reveal answer

    Consider:

    Array ( [0] => Hello [1] => world [2] => It's [3] => a [4] => beautiful [5] => day)
    The keys of an indexed array are 0, 1, 2 etc. (the index values) and values are "Hello", "world", "It's", "beautiful",
    "day".
    
  2. Question 2
    Entry

    What is the use of ini_set() ?

    • PHP
    Reveal answer

    PHP allows the user to modify some of its settings mentioned in php.ini using ini_set(). This function requires two string arguments. First one is the name of the setting to be modified and the second one is the new value to be assigned to it. Given line of code will enable the display_error setting for the script if it’s disabled.

    ini_set('display_errors', '1');
    

    We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.

  3. Question 3
    Entry

    What is the return type of a function that doesn't return anything?

    • PHP
    Reveal answer

    void which mean nothing.

  4. Question 4
    Entry

    What is the difference between == and === ?

    • PHP
    Reveal answer

    The operator == casts between two different types if they are different The === operator performs a ' typesafe comparison' That means that it will only return true if both operands have the same type and the same value.

    1 === 1: true
    1 == 1: true
    1 === "1": false
    // 1 is an integer, "1" is a string
    1 == "1": true
    // "1" gets casted to an integer, which is 1
    "foo" === "foo": true
    // both operands are strings and have the same value
    
  5. Question 5
    Entry

    What is the purpose of php.ini file?

    • PHP
    Reveal answer

    The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version.

  6. Question 6
    Entry

    What does $GLOBALS mean?

    • PHP
    Reveal answer

    $GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.

  7. Question 7
    Entry

    How can you pass a variable by reference?

    • PHP
    Reveal answer

    To be able to pass a variable by reference, we use an ampersand in front of it, as follows:

    $var1 = &$var2
    

Junior questions

26 questions
  1. Question 1
    Junior

    When should I use require vs include ?

    • PHP
    Reveal answer

    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. My suggestion is to just use require_once 99.9% of the time. Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

  2. Question 1
    Junior

    What is the difference between single-quoted and double- quoted strings in PHP?

    • PHP
    Reveal answer

    Single quoted strings will display things almost completely "as is." Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. Things get evaluated in double quotes but not in single:

    $s = "dollars";
    echo 'This costs a lot of $s.';
    // This costs a lot of $s.
    echo "This costs a lot of $s.";
    // This costs a lot of dollars.
    
  3. Question 2
    Junior

    Differentiate between echo and print()

    • PHP
    Reveal answer

    echo and print are more or less the same. They are both used to output data to the screen. The differences are: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is faster than print.

  4. Question 3
    Junior

    What do we mean by keys and values?

    • PHP
    Reveal answer

    In associative arrays, we can use named keys that you assign to them. There are two ways to create an associative array:

    // first way -
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");`// another method -
    $age['Peter'] = "35";
    //Peter, Ben & Joe are keys
    $age['Ben'] = "37";
    //35, 37 & 43 are values
    $age['Joe'] = "43";
    
  5. Question 4
    Junior

    What is PDO in PHP?

    • PHP
    Reveal answer

    PDO stands for PHP Data Object. It is a set of PHP extensions that provide a core PDO class and database, specific drivers. It provides a vendor- neutral, lightweight, data-access abstraction layer. Thus, no matter what database we use, the function to issue queries and fetch data will be same. It focuses on data access abstraction rather than database abstraction.

  6. Question 5
    Junior

    What is the differences between $a != $b and $a !== $b ?

    • PHP
    Reveal answer
    != means
    inequality (TRUE if b) and !== means
    non-identity (TRUE if b).
    
  7. Question 6
    Junior

    In PHP, objects are they passed by value or by reference?

    • PHP
    Reveal answer

    In PHP, objects passed by value.

  8. Question 7
    Junior

    How is it possible to set an infinite execution time for PHP script?

    • PHP
    Reveal answer

    The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error 'maximum execution time exceeded.' It is also possible to specify this in the php.ini file.

  9. Question 8
    Junior

    What are PSRs? Choose 1 and briefly describe it.

    • PHP
    Reveal answer

    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.

  10. Question 8
    Junior

    Declare some function with default parameter

    • PHP
    Reveal answer

    Consider:

    function showMessage($hello = false){
      echo ($hello) ? 'hello' : 'bye';
    }
    aisnotequalto aisnotidenticalto
    
  11. Question 9
    Junior

    What are the different scopes of variables?

    • PHP
    Reveal answer

    Variable scope is known as its boundary within which it can be visible or accessed from code. In other words, it is the context within which a variable is defined. There are only two scopes available in PHP namely local and global scopes.

    Local variables (local scope)
    Global variables (special global scope)
    Static variables (local scope)
    Function parameters (local scope) When a variable is accessed outside its scope it will cause PHP error
    undefined variable.
    
  12. Question 9
    Junior

    Give me some real life examples when you had to use __destruct in your classes

    • PHP
    Reveal answer

    We know that __destruct is called when the object is destroyed. Logically, what happens if the object is destroyed? Well, it means it's no longer available. So if it has resources open, it makes sense to close those resources as it's being destroyed or cleaning up after itself. Also because PHP will close resources on termination

    for you doesn't mean that it's bad to explicitly close them when you no longer need them (or good to not close
    them).
    

    Some real examples are: Closing custom database connector/wrapper connection Deletion of temporary folders Cleaning up caching Spooling the queue of logging messages to db/file

  13. Question 10
    Junior

    Explain how we handle exceptions in PHP?

    • PHP
    Reveal answer

    When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception". An exception can be thrown, and caught within PHP. To handle exceptions, code may be surrounded in a try block. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Exceptions can be

    thrown (or re-thrown) within a catch block.
    

    Consider:

    try {
      print "this is our try block n";
      throw new Exception();
    } catch (Exception $e) {
      print "something went wrong, caught yah! n";
    } finally {
      print "this part is always executed n";
    }
    
  14. Question 10
    Junior

    Is there a difference between isset and !empty ?

    • PHP
    Reveal answer

    empty is more or less shorthand for !isset($foo) || !$foo , and !empty is analogous to isset($foo) && $foo . empty is the same as !$foo , but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.

  15. Question 11
    Junior

    Is multiple inheritance supported in PHP?

    • PHP
    Reveal answer

    PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'.

  16. Question 11
    Junior

    What is the difference between var_dump() and print_r() ?

    • PHP
    Reveal answer

    The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references. The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects. Consider:

    $obj = (object) array('qualitypoint', 'technologies', 'India');
    var_dump($obj) will display below output in the screen:
    object(stdClass)#1 (3) {
      [0]=> string(12) "qualitypoint"
      [1]=> string(12) "technologies"
    
      [2]=> string(5) "India"
    }
    

    And, print_r($obj) will display below output in the screen.

    stdClass Object (
    [0] => qualitypoint
    [1] => technologies
    [2] => India
    )
    
  17. Question 12
    Junior

    When should I use require vs include ?

    • PHP
    Reveal answer

    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. My suggestion is to just use require_once 99.9% of the time. Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

  18. Question 12
    Junior

    What does the 'var' keyword mean in PHP?

    • PHP
    Reveal answer

    It's for declaring class member variables in PHP4, and is no longer needed. It will work in PHP5, but will raise an E_STRICT warning in PHP from version 5.0.0 up to version 5.1.2, as of when it was deprecated. Since PHP 5.3, var has been un-deprecated and is a synonym for 'public'. Consider:

    class foo {
      var $x = 'y';
      // or you can use public like...
      public $x = 'y';
      //this is also a class member variables.
      function bar() {
      }
    }
    
  19. Question 13
    Junior

    Can you extend a Final defined class?

    • PHP
    Reveal answer

    No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.

  20. Question 13
    Junior

    What is stdClass in PHP?

    • PHP
    Reveal answer

    stdClass is just a generic 'empty' class that's used when casting other types to objects. stdClass is not the base class for objects in PHP. This can be demonstrated fairly easily:

    class Foo{}
    $foo = new Foo();
    echo ($foo instanceof stdClass)?'Y':'N';
    // outputs 'N'
    

    It is useful for anonymous objects, dynamic properties, etc. An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array. Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.

    //Example with StdClass
    $json = '{ "foo": "bar", "number": 42 }';
    $stdInstance = json_decode($json);
    
    echo $stdInstance - > foo.PHP_EOL;
    //"bar"
    echo $stdInstance - > number.PHP_EOL;
    //42
    //Example with associative array
    $array = json_decode($json, true);
    echo $array['foo'].PHP_EOL;
    //"bar"
    echo $array['number'].PHP_EOL;
    //42
    
  21. Question 14
    Junior

    How can you enable error reporting in PHP?

    • PHP
    Reveal answer

    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.

  22. Question 15
    Junior

    Explain what the different PHP errors are

    • PHP
    Reveal answer

    A notice is a non-critical error saying something went wrong in execution, something minor like an undefined variable. A warning is given when a more critical error like if an include() command went to retrieve a non-existent file. In both this and the error above, the script would continue. A fatal error would terminate the code. Failure to satisfy a require() would generate this type of error, for example.

  23. Question 16
    Junior

    What's the difference between isset() and array_key_exists() ?

    • PHP
    Reveal answer

    array_key_exists will tell you if a key exists in an array and complains when $a does not exist. isset will only return true if the key/variable exists and is not null . isset doesn't complain when $a does not exist.

    Consider:

    $a = array('key1' => 'Foo Bar', 'key2' => null);
    isset($a['key1']);
    // true
    array_key_exists('key1', $a);
    // true
    isset($a['key2']);
    // false
    array_key_exists('key2', $a);
    // true
    
  24. Question 17
    Junior

    What are the main differences between const vs define

    • PHP
    Reveal answer

    The fundamental difference between const vs define is that const defines constants at compile time, whereas define defines them at run time.

    const FOO = 'BAR';
    define('FOO', 'BAR');// but
    if (...) {
      const FOO = 'BAR';
      // Invalid
    }
    if (...) {
      define('FOO', 'BAR');
      // Valid
    }
    

    Also until PHP 5.3, const could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum. An example of good const usage is to get rid of magic numbers. Define can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application. Unless you need any type of conditional or expressional definition, use consts instead of define() - simply for the sake of readability!

  25. Question 18
    Junior

    What are the differences between die() and exit() functions in PHP?

    • PHP
    Reveal answer

    There's no difference - they are the same. The only advantage of choosing die() over exit() , might be the time you spare on typing an extra letter.

  26. Question 20
    Junior

    Explain usage of enumerations in PHP

    • PHP
    Reveal answer

    PHP doesn't have native Enumerations. Depending upon use case, I would normally use something simple like the following: abstract class DaysOfWeek

    {
      const Sunday = 0;
      const Monday = 1;
      // etc.
    }
    $today = DaysOfWeek::Sunday;
    

    There is a native extension, too. SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Mid questions

28 questions
  1. Question 1
    Mid

    What is the difference between PDO's query() vs execute() ?

    • PHP
    Reveal answer

    query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues. execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Best practice is to stick with prepared statements and execute for increased security. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution.

  2. Question 1
    Mid

    What are the exception class functions?

    • PHP
    Reveal answer

    There are following functions which can be used from Exception class.

    getMessage() − message of exception
    getCode() − code of exception
    getFile() − source filename
    getLine() − source line
    getTrace() − n array of the backtrace()
    getTraceAsString() − formated string of trace
    

    Exception::__toString gives the string representation of the exception.

  3. Question 2
    Mid

    When should I use require_once vs require ?

    • PHP
    Reveal answer

    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. My suggestion is to just use require_once 99.9% of the time. Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

  4. Question 2
    Mid

    What is the difference between a PHP interpreter and a PHP handler?

    • PHP
    Reveal answer

    A PHP Handler is an Apache module that is used by Apache to communicate with the Php Interpreter. It is basically used by Apache to handle requests for Php files. There are different types of Php Handlers. For example mod_php is an Apache module for Php. mod_fcgid allows communication with the php_fpm interpreter over a TCP or Unix socket. The **PHP Interpreter **is an application that executes Php code one line at a time. The output of the Php Interpreter is sent to the Php Handler. This output may be processed by other Apache modules such as mod_deflate or mod_security. The final output is sent out of the TCP socket that Apache listens on.

  5. Question 3
    Mid

    How would you create a Singleton class using PHP?

    • PHP
    Reveal answer
    /**
    * Singleton class
    *
    */
    final class UserFactory {
      /**
      * Call this method to get singleton
      *
      * @return UserFactory
      */
      public static
      function Instance() {
        static $inst = null;
        if ($inst === null) {
          $inst = new UserFactory();
        }
      return $inst;
    
    }/**
    * Private ctor so nobody else can instantiate it
    *
    */
    private
    function __construct() {
    }
    }
    

    To use:

    $fact = UserFactory::Instance();
    $fact2 = UserFactory::Instance();
    But:
    $fact = new UserFactory()
    Throws an error.
    
  6. Question 3
    Mid

    Why do we use extract() ?

    • PHP
    Reveal answer

    The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success. Example:

    $a = "Original";
    $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
    extract($my_array);
    echo "\$a = $a; \$b = $b; \$c = $c";
    

    Output:

    $a = Cat; $b = Dog; $c = Horse
    
  7. Question 4
    Mid

    Maximum how many arguments are allowed in a function in PHP?

    • PHP
    Reveal answer

    There is no limit but you can use func_get_args() , func_get_arg() and func_num_args() to avoid writing all the arguments in the function definition.

  8. Question 4
    Mid

    What is the difference between MySQL, MySQLi and PDO?

    • PHP
    Reveal answer

    There are (more than) three popular ways to use MySQL from PHP:

    1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
    2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
    3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned. I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.
  9. Question 5
    Mid

    Explain function call by reference

    • PHP
    Reveal answer

    In case of call by reference, actual value is modified if it is modified inside the function. In such case, we need to use & symbol with formal arguments. The & represents reference of the variable. Example:

    function adder(&$str2) {
      $str2 .= 'Call By Reference';
    }
    $str = 'This is ';
    adder($str);
    echo $str;
    

    Output:

    This is Call By Reference
    
  10. Question 5
    Mid

    Does PHP support method overloading?

    • PHP
    Reveal answer

    Method overloading is the phenomenon of using same method name with different signature. You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

    function myFunc() {
      for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
      }
    }/*
    Argument 0: a
    Argument 1: 2
    Argument 2: 3.5
    */
    myFunc('a', 2, 3.5);
    
  11. Question 6
    Mid

    Differentiate between parameterised and non parameterised functions

    • PHP
    Reveal answer

    Non parameterised functions don't take any parameter at the time of calling. Parameterised functions take one or more arguments while calling. These are used at run time of the program when output depends on dynamic values given at run time There are two ways to access the parameterised function: 1. call by value: (here we pass the value directly ) 2. call by reference: (here we pass the address location where the value is stored)

  12. Question 7
    Mid

    Differentiate between exception and error

    • PHP
    Reveal answer

    Recovering from Error is not possible. The only solution to errors is to terminate the execution. Where as you can recover from Exception by using either try-catch blocks or throwing exception back to caller. You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be handled using try-catch blocks and can make program flow normal if they happen. Exceptions are related to application where as Errors are related to environment in which application is running.

  13. Question 8
    Mid

    What is autoloading classes in PHP?

    • PHP
    Reveal answer

    With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error. The spl_autoload_register() function in PHP can register any number of autoloaders, enable classes and interfaces to autoload even if they are undefined.

    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. The spl_autoload_register()
    function will automatically load Class1.php and Class2.php.
    
  14. Question 9
    Mid

    What are some of the big changes PHP has gone through in the past few years?

    • PHP
    Reveal answer

    Some big ones: PHP 5.0 realised the object model (AKA OOP). 5.1 added PDO - for accessing databases. 5.3 - added namespace support and late static bindings.

  15. Question 10
    Mid

    Are Parent constructors called implicitly inside a class constructor?

    • PHP
    Reveal answer

    No, a parent constructor have to be called explicitly as follows:

    parent::constructor($value)
    
  16. Question 11
    Mid

    What is the difference between using self and $this ?

    • PHP
    Reveal answer

    Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this-

    member for non-static members, use self::$member for static members. There is another aspect of self:: that is worth mentioning. Annoyingly self:: refers to the scope at the point of definition not at the point of execution. PHP 5.3 has a solution, the static:: resolution operator implements " late static binding" which is a fancy way of saying that it's bound to the scope of the class called. So $this-> refers to the current object (an instance of a class), whereas static:: refers to a class.

  17. Question 12
    Mid

    How would you create a Singleton class using PHP?

    • PHP
    Reveal answer
    /**
    * Singleton class
    *
    */
    final class UserFactory {
      /**
      * Call this method to get singleton
      *
      * @return UserFactory
      */
      public static
      function Instance() {
        static $inst = null;
        if ($inst === null) {
          $inst = new UserFactory();
        }
      return $inst;
    }/**
    * Private ctor so nobody else can instantiate it
    *
    */
    private
    function __construct() {
    }
    }
    

    To use:

    $fact = UserFactory::Instance();
    $fact2 = UserFactory::Instance();
    But:
    $fact = new UserFactory()
    Throws an error.
    
  18. Question 13
    Mid

    Explain the difference between exec() vs system() vs passthru() ?

    • PHP
    Reveal answer

    exec() is for calling a system command, and perhaps dealing with the output yourself. system() is for executing a system command and immediately displaying the output - presumably text. passthru() is for executing a system command which you wish the raw return from - presumably something binary.

  19. Question 14
    Mid

    What exactly is the the difference between array_map , array_walk and array_filter ?

    • PHP
    Reveal answer

    array_walk takes an array and a function F and modifies it by replacing every element x with F(x). array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements. array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

  20. Question 15
    Mid

    What is the difference between MySQL, MySQLi and PDO?

    • PHP
    Reveal answer

    There are (more than) three popular ways to use MySQL from PHP:

    1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
    2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
    3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned. I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.
  21. Question 15
    Mid

    Explain the difference between shell_exec() and exec()

    • PHP
    Reveal answer

    shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specified as the second parameter.

  22. Question 17
    Mid

    What is use of Null Coalesce Operator?

    • PHP
    Reveal answer

    Null coalescing operator returns its first operand if it exists and is not NULL. Otherwise it returns its second operand. Example:

    $name = $firstName ?? $username ?? $placeholder ?? "Guest";
    
  23. Question 17
    Mid

    Is there any reason to use strcmp() for strings comparison?

    • PHP
    Reveal answer

    The reason to use it is because strcmp returns < 0 if str1 is less than str2 ; > 0 if str1 is greater than str2 , and 0 if they are equal. === only returns true or false, it doesn't tell you which is the "greater" string.

  24. Question 18
    Mid

    Is there a function to make a copy of a PHP array to another?

    • PHP
    Reveal answer

    In PHP arrays are assigned by copy, while objects are assigned by reference so PHP will copy the array by default. References in PHP have to be explicit:

    $a = array(1,2);
    $b = $a;
    // $b will be a different array
    $c = &$a;
    // $c will be a reference to $a
    
  25. Question 18
    Mid

    Check if PHP array is associative

    • PHP
    Reveal answer

    Consider:

    function has_string_keys(array $array) {
      return count(array_filter(array_keys($array), 'is_string')) > 0;
    }
    

    If there is at least one string key, $array will be regarded as an associative array.

  26. Question 19
    Mid

    Does PHP support method overloading?

    • PHP
    Reveal answer

    Method overloading is the phenomenon of using same method name with different signature. You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so

    you cannot have two functions with the same name. You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

    function myFunc() {
      for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
      }
    }/*
    Argument 0: a
    Argument 1: 2
    Argument 2: 3.5
    */
    myFunc('a', 2, 3.5);
    
  27. Question 20
    Mid

    How do I pass variables and data from PHP to JavaScript?

    • PHP
    Reveal answer

    There are actually several approaches to do this: Use AJAX to get the data you need from the server. Consider get-data.php:

    echo json_encode(42);
    

    Consider index.html:

    
    Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
    
    ```jsx
    <div id="dom-target" style="display: none;">
    <?php
    $output = "42";
    // Again, do some operation, get the output.
    echo htmlspecialchars($output);
    /* You have to escape because the result
    
    will not be valid HTML otherwise. */
    ?>
    </div>
    <script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
    </script>
    

    Echo the data directly to JavaScript.

  28. Question 20
    Mid

    When should I use require_once vs require ?

    • PHP
    Reveal answer

    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. My suggestion is to just use require_once 99.9% of the time. Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

Senior questions

16 questions
  1. Question 2
    Senior

    Compare MySQLi or PDO - what are the pros and cons?

    • PHP
    Reveal answer

    Let's name some: PDO is the standard, it's what most developers will expect to use. Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point. A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. PDO has some features that help agains SQL injection In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful. inserts - almost equal, selects - mysqli is 2.5% faster for non- prepared statements/6.7% faster for prepared statements.

  2. Question 3
    Senior

    Is PHP single or multi threaded?

    • PHP
    Reveal answer

    PHP is not single threaded by nature. It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn't have a thread based architecture whatever. In the most common Windows setup and some more advanced unix setups, PHP can and does operate multiple interpreter threads in one process.

    PHP as an interpreter had support for multi-threading since the year 2000.

  3. Question 4
    Senior

    Does PHP have threading?

    • PHP
    Reveal answer

    Standard php does not provide any multithreading but there is an (experimental) extension that actually does - pthreads . The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option.

  4. Question 5
    Senior

    Explain the Exception Hierarchy introduced in PHP7

    • PHP
    Reveal answer

    Prior to PHP 7 alpha-2, the exception hierarchy in PHP 7 was different. Fatal and recoverable errors threw instances of EngineException , which did not inherit from Exception. Both Exception and EngineException inherited from BaseException . To unite the two exception branches, Exception and Error both implement a new interface, Throwable. So the new hierarchy is: |- Exception implements Throwable |- … |- Error implements Throwable |- TypeError extends Error |- ParseError extends Error |- ArithmeticError extends Error |- DivisionByZeroError extends ArithmeticError |- AssertionError extends Error

  5. Question 6
    Senior

    What is use of Spaceship Operator?

    • PHP
    Reveal answer

    This <=> operator will offer combined comparison in that it will: Return 0 if values on either side are equal Return 1 if value on the left is greater Return -1 if the value on the right is greater Consider:

    //Comparing Integers
    echo 1 <= > 1;
    //outputs 0
    echo 3 <= > 4;
    //outputs -1
    echo 4 <= > 3;
    //outputs 1
    //String Comparison
    
    echo "x" <= > "x";
    // 0
    echo "x" <= > "y";
    //-1
    echo "y" <= > "x";
    //1
    
  6. Question 6
    Senior

    Store an array as JSON or as a PHP serialized array?

    • PHP
    Reveal answer

    Problem

    You need to store a multi-dimensional associative array of data in a flat file for caching purposes. What will be your solution? Explain.

    Solution

    JSON is simpler and faster than PHP's serialization format and should be used unless: You're storing deeply nested arrays: json_decode() : "This function will return false if the JSON encoded data is deeper than 127 elements." You're storing objects that need to be unserialized as the correct class. JSON will have no memory of what the object's original class was (they are always restored as instances of stdClass ). You can't leverage __sleep() and __wakeup() with JSON You're interacting with old PHP versions that don't support json_decode

  7. Question 7
    Senior

    What does $$ mean?

    • PHP
    Reveal answer

    A syntax such as $$variable is called Variable Variable. The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string. Consider:

    $real_variable = 'test';
    $name = 'real_variable';
    echo $$name;
    

    You will get the following output : test

  8. Question 7
    Senior

    What exactly are late static bindings in PHP?

    • PHP
    Reveal answer

    Basically, it boils down to the fact that the self keyword does not follow the same rules of inheritance. self always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self will not reference the child as you might expect. Late static binding introduces a new use for the static keyword, which addresses this particular shortcoming. When you use static , it represents the class where you first use it, ie. it 'binds' to the runtime class. Consider:

    class Car {
      public static
      function run() {
        return static::getName();
      }
    private static
    function getName() {
      return 'Car';
    
    }
    }
    class Toyota extends Car {
      public static
      function getName() {
        return 'Toyota';
      }
    }
    echo Car::run();
    // Output: Car
    echo Toyota::run();
    // Output: Toyota
    
  9. Question 8
    Senior

    What are the disadvantages of using persistent connection in PDO?

    • PHP
    Reveal answer

    A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. If your script terminates unexpectedly in the middle of database operations, the next request that gets the left over connection will pick up where the dead script left off. Persistent connections are a good idea only when it takes a (relatively) long time to connect to your database. Nowadays that's almost never the case. Most modern databases (including PostgreSQL) have their own preferred ways of performing connection pooling that don't have the immediate drawbacks that plain vanilla PHP-based persistent connections do.

  10. Question 8
    Senior

    How to turn errors into exceptions in PHP?

    • PHP
    Reveal answer

    Problem

    I need to catch some warnings being thrown from some php native functions and then handle them. try/catch doesn't work because a warning is not an exception. Could you help us to turn errors into exceptions in PHP?

    Solution

    You can use set_error_handler() and the ErrorException class to turn all php errors into exceptions.

    set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
      // error was suppressed with the @-operator
      if (0 === error_reporting()) {
        return false;
      }
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    });
    try {
      dns_get_record();
    } catch (ErrorException $e) {
      // ...
    }
    

    The important thing to note when using your own error handler is that it will bypass the error_reporting setting and pass all errors (notices, warnings, etc.) to your error handler. You can set a second argument on set_error_handler() to define which error types you want to receive, or access the current setting using ... =

    error_reporting() inside the error handler.
    
  11. Question 9
    Senior

    What is the best method to merge two PHP objects?

    • PHP
    Reveal answer

    Problem

    //We have this:
    $objectA->a;
    $objectA->b;
    $objectB->c;
    $objectB->d;//We want the easiest way to get:
    
    $objectC->a;
    $objectC->b;
    $objectC->c;
    $objectC->d;
    
    ### Solution
    

    This works:

    $obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
    

    You may also use array_merge_recursive to have a deep copy behavior. One more way to do that is:

    foreach($objectA as $k => $v) $objectB->$k = $v;
    This is faster than the first answer in PHP versions < 7 (estimated 50% faster). But in PHP >= 7 the first answer
    

    is something like 400% faster.

  12. Question 10
    Senior

    Explain the Exception Hierarchy introduced in PHP7

    • PHP
    Reveal answer

    Prior to PHP 7 alpha-2, the exception hierarchy in PHP 7 was different. Fatal and recoverable errors threw instances of EngineException , which did not inherit from Exception. Both Exception and EngineException inherited from BaseException . To unite the two exception branches, Exception and Error both implement a new interface, Throwable. So the new hierarchy is: |- Exception implements Throwable |- … |- Error implements Throwable |- TypeError extends Error |- ParseError extends Error |- ArithmeticError extends Error |- DivisionByZeroError extends ArithmeticError |- AssertionError extends Error

  13. Question 11
    Senior

    Is PHP single or multi threaded?

    • PHP
    Reveal answer

    PHP is not single threaded by nature. It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn't have a thread based architecture whatever. In the most common Windows setup and some more advanced unix setups, PHP can and does operate multiple interpreter threads in one process.

    PHP as an interpreter had support for multi-threading since the year 2000.

  14. Question 12
    Senior

    What's better at freeing memory with PHP: unset() or $var = null ?

    • PHP
    Reveal answer
    unset() does just what its name says - unset a variable. It does not force immediate memory freeing. PHP's
    

    garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first. If you are doing $whatever = null; then you are rewriting variable's data. You might get memory freed/shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.

    unset($a) also removes $a from the symbol table and it seems that $a = null is a bit faster than it's unset()
    

    counterpart: updating a symbol table entry appears to be faster than removing it.

  15. Question 15
    Senior

    What is the crucial difference between using traits versus interfaces?

    • PHP
    Reveal answer

    A trait is essentially PHP's implementation of a mixin, and is effectively a set of extension methods which can be added to any class through the addition of the trait. The methods then become part of that class' implementation, but without using inheritance. An interface defines a set of methods that the implementing class must implement. Consider:

    trait myTrait {
      function foo() { return "Foo!"; }
      function bar() { return "Bar!"; }
    }
    class MyClass extends SomeBaseClass {
      use myTrait;
      // Inclusion of the trait myTrait
    }
    

    PHP, like many other languages, uses a single inheritance model - meaning that a class can derive from multiple interfaces, but not multiple classes. However, a PHP class can have multiple trait inclusions - which allows the programmer to include reusable pieces - as they might if including multiple base classes.

  16. Question 16
    Senior

    What exactly are late static bindings in PHP?

    • PHP
    Reveal answer

    Basically, it boils down to the fact that the self keyword does not follow the same rules of inheritance. self always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self will not reference the child as you might expect. Late static binding introduces a new use for the static keyword, which addresses this particular shortcoming. When you use static , it represents the class where you first use it, ie. it 'binds' to the runtime class. Consider:

    class Car {
      public static
      function run() {
        return static::getName();
      }
    private static
    function getName() {
      return 'Car';
    }
    }
    class Toyota extends Car {
      public static
      function getName() {
        return 'Toyota';
      }
    }
    echo Car::run();
    // Output: Car
    echo Toyota::run();
    // Output: Toyota
    

Expert questions

5 questions
  1. Question 12
    Expert

    Provide some ways to mimic multiple constructors in PHP

    • PHP
    Reveal answer

    Problem

    It's known you can't put two __construct functions with unique argument signatures in a PHP class but I'd like to do something like this: class Student

    {
      protected $id;
      protected $name;
      // etc.
      public function __construct($id){
        $this->id = $id;
        // other members are still uninitialised
      }
    public function __construct($row_from_database){
      $this->id = $row_from_database->id;
      $this->name = $row_from_database->name;
      // etc.
    }
    }
    

    What is the best way to achieve this in PHP?

    Solution

    I'd probably do something like this: class Student

    {
      public function __construct() {
        // allocate your stuff
      }
    public static function withID( $id ) {
      $instance = new self();
      $instance->loadByID( $id );
      return $instance;
    }
    public static function withRow( array $row ) {
      $instance = new self();
      $instance->fill( $row );
      return $instance;
    }
    protected function loadByID( $id ) {
      // do query
      $row = my_awesome_db_access_stuff( $id );
      $this->fill( $row );
    }
    protected function fill( array $row ) {
      // fill all properties from array
    
    }
    }
    

    Then if i want a Student where i know the ID:

    $student = Student::withID( $id );
    

    Technically you're not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way. Another way is to use the mix of factory and fluent style: class Student

    {
      protected $firstName;
      protected $lastName;
      // etc.
      /**
      * Constructor
      */
      public function __construct() {
        // allocate your stuff
      }/**
    * Static constructor / factory
    */
    public static function create() {
      $instance = new self();
      return $instance;
    }/**
    * FirstName setter - fluent style
    */
    public function setFirstName( $firstName) {
      $this->firstName = $firstName;
      return $this;
    }/**
    * LastName setter - fluent style
    */
    public function setLastName( $lastName) {
      $this->lastName = $lastName;
      return $this;
    }
    }// create instance
    $student= Student::create()->setFirstName("John")->setLastName("Doe");
    
  2. Question 13
    Expert

    Are PDO prepared statements sufficient to prevent SQL injection?

    • PHP
    Reveal answer

    Problem

    Let's say I have code like this:

    $dbh = new PDO("blahblah");
    $stmt = $dbh->prepare('SELECT * FROM users where username = :username');
    $stmt->execute( array(':username' => $_REQUEST['username']) );
    

    Is that truly all I need to do to avoid SQL injections? Is it really that easy?

    Solution

    The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks. For certain obscure edge-cases for example:

    $pdo->query('SET NAMES gbk');
    $var = "\xbf\x27 OR 1=1 /*";
    $query = 'SELECT * FROM test WHERE name = ? LIMIT 1';
    $stmt = $pdo->prepare($query);
    $stmt->execute(array($var));
    

    The rendered query will be that will return more than 1 row: SELECT * FROM test WHERE name = '�' OR 1=1

    /*' LIMIT 1
    
  3. Question 18
    Expert

    What does a $$$ mean in PHP?

    • PHP
    Reveal answer

    A syntax such as $$variable is called Variable Variable. Let's give the $$$ a try:

    $real_variable = 'test';
    $name = 'real_variable';
    // variable variable for real variable
    $name_of_name = 'name';
    // variable variable for variable variable
    echo $name_of_name . '<br />';
    echo $$name_of_name . '<br />';
    echo $$$name_of_name . '<br />';
    

    And here's the output : name real_variable test

  4. Question 19
    Expert

    Explain the Order of Precedence for Traits in PHP totalthereferenceto

    • PHP
    Reveal answer
    **Traits are overridden if the method with the same name is defined in the class that uses the traits. **The
    

    precedence order is that members from the current class override Trait methods, which in turn override inherited methods. Consider:

    class BaseClass {
      function SomeMethod() {
        /* Do stuff here */ }
    }
    interface IBase {
      function SomeMethod();
    }
    trait myTrait {
      function SomeMethod() {
        /* Do different stuff here */ }
    }
    class MyClass extends BaseClass implements IBase {
      use myTrait;
      function SomeMethod() {
        /* Do a third thing */ }
    }
    

    When creating an instance of MyClass, above, the following occurs:

    1. The Interface IBase requires a parameterless function called SomeMethod() to be provided.
    2. The base class BaseClass provides an implementation of this method - satisfying the need.
    3. The trait myTrait provides a parameterless function called SomeMethod() as well, which takes precedence over the BaseClass -version
    4. The class MyClass provides its own version of SomeMethod() - which takes precedence over the trait - version.
  5. Question 20
    Expert

    How could we implement method overloading in PHP?

    • PHP
    Reveal answer

    You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally. Consider:

    function myFunc() {
      for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
      }
    }/*
    
    Argument 0: a
    Argument 1: 2
    Argument 2: 3.5
    */
    myFunc('a', 2, 3.5);