PHP Interview Questions and Answers:
Following are the list of questions that are generally asked in the interview questions. These contain basic as well as advanced level PHP interview questions. Here we will try to cover as much as possible.
For PHP coding interview questions you can check this link.
Let's begin with it.
For PHP coding interview questions you can check this link.
Let's begin with it.
1. What is PHP and who invented it?
Answer:
PHP stands for PHP Hypertext Preprocessor. It is an open-source general-purpose programming language designed for web development
Previously, it was called as Personal Home Page. But later it was renamed as PHP Hypertext Preprocessor.
Rasmus Lerdorf is the inventor/father of PHP.
Rasmus Lerdorf is the inventor/father of PHP.
2. When can we use PHP?
Answer:
PHP is mainly focused on server-side scripting, so other than CGI program, it can collect form data, generate dynamic page content, send and receive cookies.
Apart from this, the main areas where PHP scripts are used.
Apart from this, the main areas where PHP scripts are used.
i. Command-line scripting.
ii. Server-side scripting.
iii. Writing desktop applications. Using PHP's advanced features in client-side applications, we can also use PHP-GTK to write such programs.
ii. Server-side scripting.
iii. Writing desktop applications. Using PHP's advanced features in client-side applications, we can also use PHP-GTK to write such programs.
3. What is include, include_once & require, require_once in PHP?
Answer:
These are the PHPs inbuilt functions that are mainly used to import OR include PHP file(s) into our code file.
It actually means that, instead of writing long lines of code in the same file, we can divide it into several files(depending upon the functionality) & then include them in the files wherever required.
Let's take an example-
db.config.php
It actually means that, instead of writing long lines of code in the same file, we can divide it into several files(depending upon the functionality) & then include them in the files wherever required.
Let's take an example-
db.config.php
<?php $host = '127.0.0.1'; $username='root'; $password = 'root'; $db_name='include_db_test'; $db_conn = mysql_connect($host', $username, $password); if (!$db_conn) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db($db_name, $db_conn ); if (!$db_selected) { die ('Can\'t connect to DB : ' . mysql_error()); } mysql_close($db_conn); ?>
Then we will include this file individually into respective class files as follows-
event.class.php
about_us.class.php
Here, we've included db.config.php file into two separate files because we can not write the whole set of code from db.config.php file into the event.class.php & about_us.class.php files separately.
The reason for this is that, if in the future, we changed the $db_name OR password of the MySQL server then we've to make changes in each individual page(s) where we wrote DB connection code. By writing into a separate file (db.config.php) we not only increase readability but also saves valuable to make changes into the individual page and of course a human error.
So,
include takes a file name as a string parameter and then include all the code from that file in the current file. If that file is not present then it will just generate a warning and the rest of the code will work as it is.
include_once takes a file name as a string parameter and if it is found that this file is already included then it will just ignore this inclusion.
require takes a file name as a string parameter and if it is not found then it will generate a fatal error and will stop the execution of the script.
require_once takes a file name as a string parameter and if it is found that this file is already included then it will just ignore this inclusion.
PHP script can be run from Command Line Interface(CLI) and for that we need to specify the script file name to be executed as follows-
event.class.php
<?php include_once("db.config.php"); .. code ?>
about_us.class.php
<?php include_once("db.config.php"); .. code ?>
Here, we've included db.config.php file into two separate files because we can not write the whole set of code from db.config.php file into the event.class.php & about_us.class.php files separately.
The reason for this is that, if in the future, we changed the $db_name OR password of the MySQL server then we've to make changes in each individual page(s) where we wrote DB connection code. By writing into a separate file (db.config.php) we not only increase readability but also saves valuable to make changes into the individual page and of course a human error.
So,
include takes a file name as a string parameter and then include all the code from that file in the current file. If that file is not present then it will just generate a warning and the rest of the code will work as it is.
include_once takes a file name as a string parameter and if it is found that this file is already included then it will just ignore this inclusion.
require takes a file name as a string parameter and if it is not found then it will generate a fatal error and will stop the execution of the script.
require_once takes a file name as a string parameter and if it is found that this file is already included then it will just ignore this inclusion.
4. How to execute a PHP script from the command line?
Answer:PHP script can be run from Command Line Interface(CLI) and for that we need to specify the script file name to be executed as follows-
php script.class.php
5. Do PHP support multiple inheritance?
Answer:
No, PHP does not support multiple inheritance. Inheritance in PHP supports single inheritance and multi-level inheritance only.
The main reason behind php does not support multiple inheritance is that PHP suffers from the Diamond Problem. So, an alternative to this is to use Object Composition OR Interface which allows multiple inheritance.
These are called a comparison operator in PHP.
== operator is mainly used to check if the value at the left of the comparison operator is equal to or not.
Example: 1 == 1 will be evaluated to true because both the values are equal.
1 == '1' will also be evaluated to true because PHP internally will typecast string value to int if that is a digit.
1 == 'true' will be evaluated to false because we are comparing string true value to digit value.
1 == true will be evaluated to true because PHP will internally be recognized as true (as a boolean 1).
And === operator is used when we need to compare value as well as the type of the value present at the left side with the value present at the right.
Example: 1 === 1 will be evaluated to true because both the values are equal and are of the data type int.
1 === '1' will be evaluated as false because even if the values look equal but their type is now different. The left value is int and right-side value is a string.
1 === true will be evaluated to false because even if both are equal by value but their data type is different. Left side value is int and right-side value is boolean.
PHP Errors: These are situations come across when there is an unusual activity happens in the code. This means if there is any mistake in writing PHP code then it will throw an error. Basically, this is the situation that can not be handled by the program itself unlike exception. There are 4 types of errors in PHP already defined.
Notice Error: In this type of error, there is something small mistake happens in the code and hence it will just generate an error message.
Type: Run-Time Error.
e.g., Undefined variable.
Warning Error: In this type of error, it will not halt/stop code execution because this type of error will just warn the user about a mistake made in the code.
Type: Run-Time Error.
e.g.: A file is included which is not present on that server location, delete a file which is not on that server location, incorrect number of parameters in a function
Parse Error: In this type of error, it will stop the further execution of the script. Parse Error is basically a syntax error.
The main reason behind php does not support multiple inheritance is that PHP suffers from the Diamond Problem. So, an alternative to this is to use Object Composition OR Interface which allows multiple inheritance.
6. What are == and === operator in PHP?
Answer:These are called a comparison operator in PHP.
== operator is mainly used to check if the value at the left of the comparison operator is equal to or not.
Example: 1 == 1 will be evaluated to true because both the values are equal.
1 == '1' will also be evaluated to true because PHP internally will typecast string value to int if that is a digit.
1 == 'true' will be evaluated to false because we are comparing string true value to digit value.
1 == true will be evaluated to true because PHP will internally be recognized as true (as a boolean 1).
And === operator is used when we need to compare value as well as the type of the value present at the left side with the value present at the right.
Example: 1 === 1 will be evaluated to true because both the values are equal and are of the data type int.
1 === '1' will be evaluated as false because even if the values look equal but their type is now different. The left value is int and right-side value is a string.
1 === true will be evaluated to false because even if both are equal by value but their data type is different. Left side value is int and right-side value is boolean.
7. What is Error and Exception in PHP?
Answer:PHP Errors: These are situations come across when there is an unusual activity happens in the code. This means if there is any mistake in writing PHP code then it will throw an error. Basically, this is the situation that can not be handled by the program itself unlike exception. There are 4 types of errors in PHP already defined.
Notice Error: In this type of error, there is something small mistake happens in the code and hence it will just generate an error message.
Type: Run-Time Error.
e.g., Undefined variable.
Warning Error: In this type of error, it will not halt/stop code execution because this type of error will just warn the user about a mistake made in the code.
Type: Run-Time Error.
e.g.: A file is included which is not present on that server location, delete a file which is not on that server location, incorrect number of parameters in a function
Parse Error: In this type of error, it will stop the further execution of the script. Parse Error is basically a syntax error.
Type: Compile-Time Error.
e.g.: Unclosed brace, Missing or Extra parentheses, Missing semi-colon.
Fatal Error: In this type of error, it will stop the further execution of the script. This is considered to be a critical error in the code. It's basically typo in the code which PHP does not understand while calling function whether it is an in-built OR user-defined function.
Type: Compile-Time Error.
e.g.: Undefined function, missing file while using include function
PHP Exception in PHP is nothing but an unexpected situation that happened in the code while code execution. This kind of Errors can be handled by the program itself.
PHP provides the following keywords for handling an exception.
Fatal Error: In this type of error, it will stop the further execution of the script. This is considered to be a critical error in the code. It's basically typo in the code which PHP does not understand while calling function whether it is an in-built OR user-defined function.
Type: Compile-Time Error.
e.g.: Undefined function, missing file while using include function
PHP Exception in PHP is nothing but an unexpected situation that happened in the code while code execution. This kind of Errors can be handled by the program itself.
PHP provides the following keywords for handling an exception.
1. try{} - This is the block of code where we think an exception may occur.
2. catch(){} - This is the block of code where we will handle an exception. This block of code will execute once an exception occurred.
3. throw - It is used to throw an exception.
4. finally{} - This block of code can be specified instead or after of catch blocks. Code inside finally{} will always be executed after try{} and catch(){} block and before normal execution resumes regardless of whether an exception has been thrown.
8. What is mysql_pconnect() useful for?
Answer:
When we connect our code to interact with the database, then there are two types of connections we can make with the MySQL server.
i. mysql_connect()
ii. mysql_pconnect()
Here, p in the mysql_pconnect() stands for persistent which means that as soon as we connect our via mysql_pconnect() with Mysql Server then that connection remains open. It means that the connection does not close when the PHP script ends.
There are mainly two differences between mysql_connect() & mysql_pconnect().
i. Whenever we try to connect to the Mysql server then mysql_pconnect() function will first try to find the open connection with the same host, username and password. When it gets such a connection, then that instance is returned instead of opening a new connection.
ii. As mentioned above, a connection will stay open even PHP script execution ends.
i. mysql_connect()
ii. mysql_pconnect()
Here, p in the mysql_pconnect() stands for persistent which means that as soon as we connect our via mysql_pconnect() with Mysql Server then that connection remains open. It means that the connection does not close when the PHP script ends.
There are mainly two differences between mysql_connect() & mysql_pconnect().
i. Whenever we try to connect to the Mysql server then mysql_pconnect() function will first try to find the open connection with the same host, username and password. When it gets such a connection, then that instance is returned instead of opening a new connection.
ii. As mentioned above, a connection will stay open even PHP script execution ends.
9. What is the difference between mysql_fetch_object() and mysql_fetch_array()?
Answer:
mysql_fetch_object() is mainly used to fetch the first single matching record from the MySQL query result as an object while
mysql_fetch_array() is used to fetch all the records from the Mysql query result as an array.
mysql_fetch_array() is used to fetch all the records from the Mysql query result as an array.
10. How to check if the value of a given variable is a number?
Answer:
PHP has provided an inbuilt function is_numeric() that will identify whether a given variable is a number OR not.
For Example:
$id = '123'; if(is_numeric($id)) { echo $id . ' is a number'; } else { echo $id . ' is NOT a number'; }
// output
123 is a number.
$id = 'test123'; if(is_numeric($id)) { echo $id . ' is a number'; } else { echo $id . ' is NOT a number'; }
// output
test123 is NOT a number
$id = '123test'; if(is_numeric($id)) { echo $id . ' is a number'; } else { echo $id . ' is NOT a number'; }
// output
123test is NOT a number
11. What is unset() and unlink() function in PHP OR what is the difference between unset() and unlink() ?
Answer:
unset() - As the name indicates, it unsets the provided variable. It means, it destroys the variable (provided).
unlink() - This function is mainly used to perform the delete operation on the file.
12. Is PHP a strongly typed language?
Answer:
No, PHP is not a strongly typed language. Rather is loosely typed language. As in other programming languages like Java and C#, we can define the type of the variable as int, string, boolean before accessing it. But in the PHP, PHP parser implicitly identifies the type of the variable depending on the way it is defined.
For Example-
This variable is identified as integer.
This variable is identified as boolean.
13. What is variable variables ($$) in PHP?
Answer:
When we use value of one variable as a name of other variable then that is called as variable variables. In PHP, it is declared with two $ signs as $$.
For example-
$type = 'language'; $$type = 'PHP'; // we can use this different format as- echo "Name of the Programming $type is $language".PHP_EOL; // OR echo "Name of the Programming $type is ${$type}".PHP_EOL; // In above example first it will print $type value as language and the using ${language} it will print PHP
Then, the main question arises-
14. Why we need to use variable variables ( $$ )?
Answer:
Variable variables are also known as a dynamic variable. The main purpose of using variable variables is to -
1. Reduce number of lines of code.
2. Easy change in the variables name.
Now, question arises how?
Let's see the example-
$emp_info = ['id' => 123,'name' => 'Andrew', 'age' => '30', 'address' => 'washington, D.C.']; $id = $emp_info['id']; $name = $emp_info['name']; $age = $emp_info['age']; $address = $emp_info['address']; echo $id; echo $name; echo $age; echo $address;// output
123
Andrew
30
washington, D.C.
Here, as we can see to access each element of an array we have to explicitely access it via $emp_info variable and provide value of each element in the separate variable. More the number of an array element more will be the declaration.
So, we can solve this problem via using variables variable and as we know that-
variables declared inside foreach can be accessed outside of the foreach loop as well.
So, lets rewrite our exising code using variables variable.
$emp_info = ['id' => 123,'name' => 'Andrew', 'age' => '30', 'address' => 'washington, D.C.']; foreach($emp_info as $k=>$y){ $$k = $y; } echo $id; echo $name;
Here, we've used an array as an example, there may be form fields which we need to sanitize. So, to filter each and every value of an array OR form elements, we will loop through each element and the assign each field in the variable. Now, each key becomes variable and this is how variable variables will be useful.
15. How to stop execution of PHP script ?
Answer:
PHP has provided two in-built function to stop further execution of the code.
1. die(); - is an equivalent to exit() and used to stop the further execution of the code
2. exit(); - same as above. To stop the further execution of the code.
16. How to increase the maximum execution time of a script in PHP?
Answer:
We can change the execution time of the PHP script by changing the configuration for execution time in php.ini file.
php.ini file is the main configuration file in php where we can set many different configurations as per our requirement.
e.g., To set php script execution time to 1600 secs then make such changes in php.ini file as follows-
max_execution_time = 1600
17. What will happen when our script takes more than the value of max_execution_time?
Answer:PHP will throw a fatal error once execution time of current script takes more than predefined time in php.ini file which eventually will stop the further execution of the script.
Fatal error: Maximum execution time of 1600 seconds exceeded in C:\xampp\htdocs\project\file.php on line 32
18. What is the solution to solve Maximum execution time exceeded fatal error?
Answer:To solve this issue we have two options -
1. Change the existing code in such a way that it will not exceed maximum execution time error because this will cause performance issue of the website.
2. Increase the max_execution_time to higher value.
19. How to check the data-type of any variable in PHP?
Answer:
PHP has provided in-built function (gettype()) to check the type of the value.
$int_check = 777; echo gettype($int_check); // integer $string_check = 'PHP'; echo gettype($string_check); // string $boolean_check = TRUE; echo gettype($boolean_check); //boolean
One other option to know the data-type of the value is using var_dump();
$int_check = 777; var_dump($int_check); // int(777) $string_check = 'PHP'; var_dump($string_check); // string(3) "PHP" $boolean_check = TRUE; var_dump($boolean_check); //bool(true)
But there is a basic difference between these functions-
gettype() - is the direct function to tell the type of the value.
var_dump() - is the function which will tell the type(in short form like int, string, bool) as well as the value. But if the value is a string then it will also tell us about the character count of that string.
20. Does PHP support Type casting?
Answer:Yes, PHP supports type casting. As we know that PHP does not support declaration of data type for variable (until PHP 7.4). So, type casting any variable to any data-type by using following syntax-
$int_check = 777; $bool_check = (bool) $int_check; echo gettype($bool_check);
// output
boolean
No comments:
Post a Comment