Categories Interview Question

PHP Interview

1) What is PHP?

  • PHP stands for Hypertext Preprocessor.
  • It is an open source server-side scripting language which is widely used for web development.
  • It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.

2) What is PEAR in PHP?

  • PEAR is a framework and repository for reusable PHP components.
  • PEAR stands for PHP Extension and Application Repository.
  • It contains all types of PHP code snippets and libraries.
  • It also provides a command line interface to install “packages” automatically.

3) Who is known as the father of PHP?
Rasmus Lerdorf

4) What was the old name of PHP?
Personal Home Page.

5) Explain the difference b/w static and dynamic websites?

In static websites, 

  • content can’t be changed after running the script.
  • You can’t change anything in the site.
  • It is predefined.

In dynamic websites, 

  • content of script can be changed at the run time.
  • Its content is regenerated every time a user visit or reload. Google, yahoo and every search engine is the example of dynamic website.

6) What is the name of scripting engine in PHP?
The scripting engine that powers PHP is called Zend Engine 2.

7) Explain the difference between PHP4 and PHP5.
PHP4 doesn’t support oops concept and uses Zend Engine 1.
PHP5 supports oops concept and uses Zend Engine 2.

8) What are the popular Content Management Systems (CMS) in PHP?

  • WordPress
  • Joomla
  • Magento
  • Drupal

9) What are the popular frameworks in PHP?

  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework

10) Which programming language does PHP resemble to?
PHP has borrowed its syntax from Perl and C.

11) List some of the features of PHP7.

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator (??)
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Closure::call method
  • Group use declaration
  • Generator return expressions
  • Generator delegation
  • Space ship operator

12) What is “echo” in PHP?

  • PHP echo output one or more string.
  • It is a language construct not a function.
  • So use of parentheses is not required.
  • But if you want to pass more than one parameter to echo, use of parentheses is required.

Syntax:
void echo ( string $arg1 [, string $… ] )

13) What is “print” in PHP?

  • PHP print output a string.
  • It is a language construct not a function.
  • So use of parentheses is not required with the argument list. Unlike echo, it always returns 1.

Syntax:
int print ( string $arg)

14) What is the difference between “echo” and “print” in PHP?

    • Echo can output one or more string but print can only output one string and always returns 1.
    • Echo is faster than print because it does not return any value.

echo

  • void echo ( string $arg1 [, string $… ] )
  • Returns nothing
  • Can take multiple arguments
  • More faster than print

print

    • int print ( string $arg )
    • Returns always 1
    • Can take only one argument
    • Slower than echo

15) How a variable is declared in PHP?

  • PHP variable is a name of memory location that holds data.
  • It is a temporary storage.

Syntax:
$variableName=value; or $variableName;

16) What is the difference between $message and $$message?

  • $message stores variable data while $$message is used to store variable of variables.
  • $message stores fixed data whereas the data stored in $$message may be changed dynamically

17) What are the ways to define a constant in PHP?

  • PHP constants are name or identifier that can’t be changed during execution of the script.
  • PHP constants are defined in two ways:
    • Using define() function
    • Using const() function

18)Difference Between Functions & Language Constructs.

Language Constructs:

      • PHP constructs are the basic elements of the PHP language and hence these are known by PHP parser very well.
      • Language constructs can be used with or without parenthesis. While built-in functions can’t be used without parenthesis.
      • Fastest things in PHP are the language constructs.
      • Language constructs are relatively faster over built-in functions since they are basic elements of the language. So, always use language constructs over function if there is a language construct available i.e. using a type casting operator like (int) $var is more efficient than using the function intval($var).
      • Language constructs are keywords that are a part of the syntax of the language, i.e. they are parts of the language itself.
      • They cannot be user defined nor can they added to the language via extensions or libraries. They may or may not take arguments and they may or may not have return values (although most of them don’t).
      • Examples of language constructs in PHP include:
        • echo()
        • print()
        • die()
        • include()
        • require()
        • empty()
        • isset()
        • unset()
        • list()
        • array()

function

    • A function is a block of code which is written in such a way that it may be used and reused multiple times in the execution of a script.
    • It may be designed to accept arguments and return values or it may do neither.
    • If it is designed to take arguments, they will invariably affect the procedures of the function and, quite likely, any value(s) returned by the function.
    • In PHP, functions may be compiled with the language (referred to as core or native functions), they may be user defined (i.e. created by the programmer writing the script) or they may be accessed as components of external libraries or extensions available via PECL.
    • Examples of PHP functions include:
      • json_encode()
      • mysql_connect()
      • preg_replace()
      • strtolower()
      • array_shift()
      • unlink()
      • mail()
      • ob_start()
      • file_get_contents()
      • curl_init()

The key difference between functions and language constructs is that language constructs are the most basic units of the language and cannot be broken down further by the PHP parser whereas functions have to be further broken down before being parsed, often into language constructs. In other words, in just the same way that PHP code has to be broken down into lower level opcode by the PHP parser in order for the machine to understand it, functions must be broken down to language constructs by the PHP parser before they are parsed.

18) What are magic constants in PHP?
PHP magic constants are predefined constants which changes on the basis of their use. They start with a double underscore (__) and end with a double underscore (__).

19) How many data types are there in PHP?
PHP data types are used to hold different types of data or values. There are 8 primitive data types which are further categorized in 3 types:
Scalar types
Compound types
Special types

20) How to do single and multi line comment in PHP?
PHP single line comment is done in two ways:
Using // (C++ style single line comment)
Using # (Unix Shell style single line comment)
PHP multi line comment is done by enclosing all lines within /* */.

21) What are the different loops in PHP?
For, while, do-while and for each.

22) What is the use of count() function in PHP?
The PHP count() function is used to count total elements in the array, or something an object.

23) What is the use of header() function in PHP?
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this function.

24) What does isset() function?
The isset() function checks if the variable is defined and not null.

25) Explain PHP parameterized functions.
PHP parameterized functions are functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function. They are specified inside the parentheses, after function name. Output depends upon dynamic values passed as parameters into function.

26) Explain PHP variable length argument function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do this, you need to use 3 ellipses (dots) before the argument name. The 3 dot concept is implemented for variable length argument since PHP 5.6.

27) Explain PHP variable length argument function.
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments.

28) What is the array in PHP?
Array is used to store multiple values in single value. In PHP, it orders maps of pairs of keys and values. It stores the collection of data type.

29) How many types of array are there in PHP?
There are three types of array in PHP:
Indexed array
Associative array
Multidimensional array

30) Explain some of the PHP array functions?
There are many array functions in PHP:
array()
array_change_key_case()
array_chunk()
count()
sort()
array_reverse()
array_search()
array_intersect()

31) What is the difference between indexed and associative array?
The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For example:
$season=array(“summer”,”winter”,”spring”,”autumn”);
The associative array holds elements with name. For example:
$salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);

32) How to get the length of string?
The strlen() function is used to get the length of string.

33) Explain some of the PHP string functions?
There are many array functions in PHP:
strtolower()
strtoupper()
ucfirst()
lcfirst()
ucwords()
strrev()
strlen()

34) What are the methods to submit form in PHP?
There are two methods GET and POST.

35) How can you submit a form without a submit button?
You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.

36) What are the ways to include file in PHP?
PHP allows you to include file so that page content can be reused again. There are two ways to include file in PHP.
include
require

37) Differentiate between require and include?
Require and include both are used to include a file, but if file is not found include sends warning whereas require sends Fatal error.

38) Explain setcookie() function in PHP?
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE superglobal variable.
Syntax:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

39) How can you retrieve a cookie value?
echo $_COOKIE [“user”];

40) What is a session?
PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which is known as session.
Sessions generally store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same user.
Simply, it maintains data of an user (browser).

41) What is the method to register a variable into a session?

We can use the session_register ($ur_session_var) function.

42) What is $_SESSION in PHP?
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.

43) What is PHP session_start() and session_destroy() function?
PHP session_start() function is used to start the session. It starts a new or resumes the existing session. It returns the existing session if session is created already. If session is not available, it creates and returns new sessions.

44) What is the difference between session and cookie?
The main difference between session and cookie is that cookies are stored on user’s computer in the text fileformat while sessions are stored on the server side.
Cookies can’t hold multiple variables on the other hand Session can hold multiple variables.
You can manually set an expiry for a cookie, while session only remains active as long as browser is open.

45) Write syntax to open a file in PHP?
PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.
Syntax:
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

46) How to read a file in PHP?
PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.
PHP file read functions are given below:
fread()
fgets()
fgetc()

47) How to write in a file in PHP?
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

48) How to delete file in PHP?
The unlink() function is used to delete file in PHP.
bool unlink (string $filename)

49) What is the method to execute a PHP script from the command line?
You should just run the PHP command line interface (CLI) and specify the file name of the script to be executed as follows.

50) How to upload file in PHP?
The move_uploaded_file() function is used to upload file in PHP.
bool move_uploaded_file ( string $filename , string $destination )

51) How to download file in PHP?
The readfile() function is used to download file in PHP.
int readfile ( string $filename )

52) How can you send email in PHP?
The mail() function is used to send email in PHP.
bool mail($to,$subject,$message,$header);

53) How do you connect MySQL database with PHP?
There are two methods to connect MySQL database with PHP. Procedural and object oriented style.

54) How to create connection in PHP?
The mysqli_connect() function is used to create connection in PHP.
resource mysqli_connect (server, username, password)

55) How to create database connection and query in PHP?
Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use following 2 alternatives.
mysqli_query()
PDO::_query()

56) How can we increase execution time of a PHP script?
By default, maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the script and returns an error.
You can change the script run time by changing the max_execution_time directive in php.ini file.
When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(), then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited time.

57) What are the different types of errors in PHP?
There are 3 types of error in PHP.
Notices:These are non-critical errors. These errors are not displayed to the users.
Warnings:These are more serious errors but they do not result in script termination. By default, these errors are displayed to the user.
Fatal Errors:These are the most critical errors. These errors may cause due to immediate termination of script.

58) How to stop the execution of PHP script?
The exit() function is used to stop the execution of PHP script.

59) What are the encryption functions in PHP?
CRYPT() and MD5()

60) What is htaccess in PHP?
The .htaccess is a configuration file on Apache server. You can change configuration settings using directives in Apache configuration files like .htaccess and httpd.conf.

61) Explain PHP explode() function.
The PHP explode() function breaks a string into an array.

62) Explain PHP split() function.
The PHP split() function splits string into an array by regular expression.

63) How can we get IP address of a client in PHP?
$_SERVER[“REMOTE_ADDR”];

64) What is the difference between GET and POST?

  • GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
  • GET can handle a maximum of 2048 characters, POST has no such restrictions.
  • GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
  • Normally GET is used to retrieve data while POST to insert and updat

65) Can the value of a constant change during the script’s execution?
No, the value of a constant cannot be changed once it’s declared during the PHP execution.

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

67) What are the __construct() and __destruct() methods in a PHP class?
All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.

68) How we can get the number of elements in an array?
The count() function is used to return the number of elements in an array.

69) How would you declare a function that receives one parameter name hello?
If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
<?php
function showMessage($hello=false){
echo ($hello)?’hello’:’bye’;
}
?>

70) The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?
<?php
echo array_sum(explode(‘,’,$input));
?>

71) Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has only one field, an input text field named email. How would you validate whether the field is empty? Print a message “The email cannot be empty” in this case.
<?php
if(empty($_POST[’email’])){
echo “The email cannot be empty”;
}
?>
72)Suppose that you have to implement a class named Dragonball. This class must have an attribute named ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?
<?php
class dragonBall{
private $ballCount;

public function __construct(){
$this->ballCount=0;
}

public function iFoundaBall(){
$this->ballCount++;
if($this->ballCount===7){
echo “You can ask for your wish.”;
$this->ballCount=0;
}
}
}
?>

73) What are the 3 scope levels available in PHP and how would you define them?
Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class

74)What are getters and setters and why are they important?
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter you are able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If you are not using a setter and just declaring the $userName variable by hand you could end up with results as such: “kevin”, “KEVIN”, “KeViN”, “”, etc. With a setter you can not only adjust the value, for example, ucfirst($userName), but you can also handle situations where the data is not valid such as the example where “” is passed. The same applies to a getter – when the data is being returned, you can modify the results to include strtoupper($userName) for proper formatting further up the chain.

75)What does MVC stand for and what does each component do?
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the view. It’s responsible for interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.
The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.
The view is passed data by the controller and is displayed to the user

76) How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?
Do not output anything to the browser before using code that modifies the HTTP headers. Once you call echo or any other code that clears the buffer you can no longer set cookies or headers. That is also true for error messages, so if an error happens before you use the header command and the INI directive display_errors is set then that will also cause that error to show.

77) What does the following code output?
$i = 016;
echo $i / 2;
The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.

78) Why would you use === instead of ==?

If you know two values should have the same type then yes use Strict (===)  over loose (==) .  Strict  has better performance because it doesn’t have to do type conversion like loose  does .

For example 1 == “1”  returns true because that string gets converted to a number to check equality

While 1 === “1” returns false

Strict equality pretty much goes “not the same type?  FALSE”

There are three types of  assignment operators.

Assignment = vs Equal == vs Identical === Operators in PHP

A single equal sign = is the basic assignment operator in PHP.

Don’t think this sign as “equal to”. The variable on left side of = gets set to the value of the expression on the rights.

It is used to set a variable equal to a value or set a variable to another variable’s value.

Example’ =’

<?php
$a = 123; //assigned 123 to variable $a
$b = $a; // assigned $a
?>

In above example $a and $b has the same value 123.

Equal Operator ==

The double equal sign == is a comparison operator called Equal Operator, it accepts two inputs to compare and return true if the values are same and return false if values are not same. Keep in mind that the equality operator == is different than the assignment operator =. The assignment operator changes the variable on the left to have a new value, while the equal operator == tests for equality and returns true or false.

Example ==

<?php
$a = 123; //php integer
$b = '123'; //php string
if ($a == $b) {
echo 'Values are same';
}
else {
echo 'Values are not same';
}
?>

The above example prints Values are same.

Identical Operator ===

Identical operator === allows for stricter comparison between variables. It only returns true if the two variables or values being compared hold the same information and are of the same data type.

Example ===

<?php
$a = 123; //php integer
$b = '123'; //php string
if ($a === $b) {
echo 'Values and types are same';
}
else {
echo 'Values and types are not same';
}
?>

79)What are the different types of errors in php?

E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings

80)

Leave a Reply

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