21 PHP Basic Concepts Interview Questions & Answers
Below is a list of our PHP Basic Concepts interview questions. Click on any interview question to view our answer advice and answer examples. You may view six answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. What is the default maximum PHP script execution time? and how can you increase it?
The max. script execution time for PHP is 30 seconds (by default).
If a script takes longer than 30 seconds, then we get a fatal error, and the script is stopped.
The error looks like this:
Fatal error: Maximum execution time of 30 seconds exceeded in sample_script.php
We can increase the script execution time by going to the php.ini file. There are two relatively simple ways of increasing execution time.
1. Modify the max_execution_time value in the php.ini file and set acc. to our requirements.
2. Change the max_execution_time value by using ini_set() function as :
ini_set('max_execution_time', 300);
In this case, 300 represents seconds so this translates into 5 minutes, so the script max. execution time is set to 5 minutes.
We can follow any one of the methods above to change the PHP max. execution time.
Written by Sujal khatiwada on May 4th, 2021
2. What is the difference between echo and print in php?
In PHP both echo and print are used to output data to a browser.
echo just outputs the value in the browser's screen while print outputs and also returns 1 when we use it.
Also, we can output multiple values using echo separated by commas.
<?php
echo "123", " 456", " some other value"; // here, we're printing multiple values using commas
echo "<br />";
$the_return_value = print "user"; // we can also do print()
echo "<Br />";
echo $the_return_value; // this is the
?>
In the above coding example, we can see that we've used echo to print out multiple values just by separating with commas but print can't do that and also print returns 1 when we use print to print something.
Technically, echo is faster than print because it doesn't return any value.
Most developers do not have a preference as the difference between echo and print are small.
Written by Sujal khatiwada on May 4th, 2021
3. What is the difference between explode() and preg_split() in PHP?
The difference between explode() and preg_split() is that explode() just breaks a string using a separator but preg_split() breaks a string using a regular expression.
These functions examine your understanding of manipulating data in PHP and also the use of regular expressions.
Let's see an example below that demonstrates this issue in the code.
<?php
$friends= "Tom, Jack, Henry, Nicholas";
// using explode()
$frienda_array= explode(", ", $friends);
echo "<pre>";
print_r($frienda_array);
echo "</pre>";
// using preg_split()
$data= preg_split("/, /", $friends);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Written by Sujal khatiwada on May 4th, 2021
4. Can we access a variable defined outside of a function ( in global scope ) inside the function directly?
This question examines the concept of scope. There are two kinds of scope:
1. Local Scope
2. Global Scope
In this case we cannot access the variable defined outside the function into the function directly because they have different scopes. PHP will not allow access to a variable outside of the function directly.
<?php
$username= "test";
function send_email() {
global $username;
echo $username;
}
send_email();
?>
In the above code, we can see the global keyword in front of the variable name which we want to use is inside the function.
By writing a global keyword, we're saying that "I want to use the $username variable which is present outside the function, in global scope, inside the function."
Understanding the scope of variables is one of the important skills in becoming a great developer.
Written by Sujal khatiwada on May 4th, 2021
5. Is it possible to submit a form without a submit button in PHP, if so how?
Yes, it's possible to submit a form without a submit button by using javascript, as javascript has the submit() method available.
If you are interviewing for a full stack developer role the interviewer will often attempt to integrate some front end development questions into your interview. This is a great example of how a technical interviewer will sometimes ask how PHP is used in conjunction with other programming languages.
The code below demonstrates how to do this task.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form submission in PHP</title>
</head>
<body>
<?php
if(isset($_POST) && !empty($_POST)) {
$email = $_POST['email'];
$password = $_POST['password'];
echo $email, $password;
}
?>
<form action="" method="post" id="login-form">
<div class="form-group">
<label for="email">Enter your e-mail below</label>
<input type="email" name="email" id="email">
</div>
<div class="form-group">
<label for="password">Enter your password below</label>
<input type="password" name="password" id="password">
</div>
<div id="submit-form">Login</div>
</form>
<script>
// vars
const loginBtn= document.getElementById("submit-form");
function submitForm() {
document.getElementById("login-form").submit();
}
loginBtn.addEventListener("click", e => {
// Perform submit operation
submitForm();
e.preventDefault();
});
</script>
</body>
</html>
Let's see what's happening in the above code,
We have created a form using HTML in the above code which has email and password fields. The form has an id of login-form, we supplied this form with an id so that we can grab (select) it using Javascript and perform a submission of the form.
In the script, we are grabbing ( selecting using getElementById ) the div which is used to click and after we click on the Login text that's inside the div, the form is submitted.
It's because we've attached a click event on the Login text, which is inside the div having id of submit-form.
We have written the submitForm() function in the script just to make our code look a little bit cleaner, as the function creates a separate code block.
Written by Sujal khatiwada on May 4th, 2021
6. What are some of the different ways of defining constants in PHP?
There are 2 ways of defining constants in PHP, they are:
1. By using the define() function.
2. By using the const keyword.
The interviewer will ask this question in preparation for a more complex question. They want to understand your level of understanding and how familiar you are with the PHP syntax.
<?php
define("BASE_URL", "localhost/custom_php_insta_clone");
const USER= "root";
echo USER;
echo "<Br />";
echo BASE_URL;
?>
Important Note: constants are global and can be accessed from anywhere in the script.
There are two kinds of scope. One is local and one is global. Variables that have global scope can be accessed anywhere in the script. Whereas variables with local scope can only be accessed by certain functions.
Written by Sujal khatiwada on May 4th, 2021
7. State the four different types of errors in PHP.
Debugging is an essential part of being a software developer. A technical interviewer will want to see that you know and can explain the most common types of errors when using PHP. This knowledge in turn will make you a better developer as you will be able to troubleshoot more effectively and efficiently.
The four different types of errors in PHP are:
[1.] Fatal
[2.] Parse
[3.] Notice
[4.] Warning
A Fatal error crashes your program. These are classified as critical errors. A common cause of such an error is an undefined function or class in the script.
A Parse error is caused by misused or missing symbols in the syntax. The compiler will catch the error and terminate the script.
A Notice error is a minor error. They are similar to warning errors and will not stop the script from executing. They are normally caused by the system when it is uncertain whether a mistake has been made in the code or if that is the actual code.
A warning error does not stop the script from running. It only warns the user of a problem.
Written by Sujal khatiwada on May 4th, 2021
8. What is the difference between single quoted string and double quoted string in PHP?
A technical interviewer wants to determine if you are familiar with the subtle nuances of PHP syntax.
The primary difference between double and single quotes is that using double quotes allows you to include variables directly within the string. In PHP you often use single quotes to define a constant string like 'a' while you use double quotes to define a string contain identifier like "a $b".
See the example below:
<?php
$books = "The Harry Potter";
$author = "J.K Rowling";
echo "{$books} is written by {$author}";
echo "<br />";
echo '{$books} is written by {$author}';
?>
From the above code, we can clearly see the different output printed out on the browser.
Experiment with the single and double quotes yourself to develop familiarity with the syntax.
Written by Sujal khatiwada on May 4th, 2021
9. What is post and pre-increment in PHP ( or what's the difference between ++$i and $i++ )?
The technical interviewer wants to test your understanding of PHP syntax when asking a question like this.
Pre- increment (++i) is when the value of the variable is incremented by one BEFORE assigning a value to the variable.
Post- increment (i++) is when the value of the variable is incremented by one AFTER assigning a value to the variable.
Let's see the example below that demonstrates this concept:
<?php
$i= 10;
echo ++$i;
echo "<br />"; // we're brealing a line
echo $i++;
echo "<Br />"; // breaking a line
echo $i; // returns 12
?>
The reason why pre-increment is faster is that it just increases the value without keeping a record of the old value.
In the case of post-increment, the old value is kept in a temporary variable in memory and then the value is increased later on.
Written by Sujal khatiwada on May 4th, 2021
10. What is the difference between $ and $$ in PHP?
Put simply, the $var (single dollar) is a normal variable with the name var that stores any value like a string or an integer. The $$var (double dollar) is a reference variable that stores the value of the $var inside it.
If $var= 'user', then $$var represents $user, because the value of $var is user.
Let's see the coding example below to understand it more clearly.
<?php
$kathmandu = 'Capital of Nepal';
$customer_address = 'kathmandu';
echo $customer_address;
echo "<br />";
echo $$customer_address;
?>
In the above code, we have a $kathmandu variable and a $customer_address variable.
In this case, we're echoing out by executing the following code:
echo $$customer_address;
This code grabs the value of $customer_address which is kathmandu, and then the echo $$customer_address points to $kathmandu.
Then we have the $kathmandu variable in our PHP code also, so we get Capital of Nepal as an output printed on the browser.
Written by Sujal khatiwada on May 4th, 2021
11. What is output buffering in PHP? What are some of the benefits of output buffering?
Output Buffering (or OB for short) is the method of telling PHP to hold the output data before sending it to the browser.
In other words, it's a mechanism for controlling how much data to hold by PHP temporarily before sending it to the user (client).
Let's see a coding example that illustrates the working of the output buffer.
<?php
ob_start();
$first_string = "Hello";
echo $first_string;
$ob_first = ob_get_contents();
$second_string = " World";
echo $second_string;
$ob_second= ob_get_contents();
ob_end_clean();
echo "<pre>";
var_dump($ob_first, $ob_second);
echo "</pre>";
?>
In the above code, we have used two functions that are available in PHP, one is ob_start() and another one is ob_get_contents().
We are telling PHP to initialize the output buffer ( so that we can see its impact on our program ) by using ob_start().
In the above example, ob_get_contents() grabs all of the data gathered since we called ob_start().
So, when we do var_dump($ob_first, $ob_second); then we can see output of var_dump as:
string(5) "Hello"
string(11) "Hello World"
which means $ob_second variable contains a value that has been already printed before the world, so basically it demonstrates that ob_get_contents gets(gathers) all the previous values beginning from the initialization of the ob_start() function.
Written by Sujal khatiwada on May 4th, 2021
12. How can you display output directly into the browser using PHP (without echo or print or any other pre-defined functions)?
Content is usually displayed on your webpage with PHP echo or print statements. They both do the same thing. An echo and print statement produces output which is sent to your browser and your browser will handle the output as HTML.
In this example an interviewer might examine other ways of displaying output using PHP to your browser.
<?=1+2 ?>
We can get the output using the syntax above, so this makes typing the code a lot faster in cases where we just want to return something as an output.
<?php
$a = strtoupper("Learning to code");
$a .= " is more fun than ever";
?>
<?=$a; ?>
// Just try out this example
<?=1+10 ?>
In the above code, we've done variable initialization ( supplied value to a variable ) and then the same variable is concatenated with another string which is: " is more fun than ever " so, in the next step, we just used the short-hand syntax to output the value of the variable a.
This is an example of an alternative way of using PHP to direct an output to a browser.
Warning: we do not recommend writing your own code in this way, as some versions of PHP have not allowed this method. So it is a safer bet to write your echo statement out fully.
Written by Sujal khatiwada on May 4th, 2021
13. Write the output of the given program: $clothes= ["Gloves", "T-shirt", "Jacket", "Shoes", "Shocks"]; $clothes= array_flip($clothes); echo $clothes['T-shirt'];
The output is 1
Basically, we're creating an array in the given script and then using the array_flip() function on it.
The array_flip() function flips the keys with their associated values, so in this case, when doing echo $clothes['T-shirt'] , we get 1.
Written by Sujal khatiwada on May 4th, 2021
14. Create an array and check if a value (dummy value) is inside that array. If it is there, then join the array values with a comma and a space.
<?php
// array with usernames of Users ( assume they're usernames in array )
$users= ['username_1', 'username_2', 'username_3', 'username_3'];
if(in_array("user_2", $users)) {
// Joining array values with a comma and a space
$joined_values= implode(", ", $users);
echo "Users: ". $joined_values;
}
?>
In the above question, we are asked to join array values with a comma and space after checking if a dummy value ( in this case it's user_2) is inside the $users array.
So, first, we check if the dummy value is present inside the $users array or not by using the in_array() function that is already available for us in the PHP language.
The user_2 is present in the $users array, so the "if block" is executed. As a result, the implode() function is called and it joins the array values.
We should note that the implode() function takes 2 parameters, the first one is a string used to join 2 array values and the second one is the array we want to use.
In the end, we did an extra step to output the result using echo which outputs the whole string that contains the returned string from the $implode() function.
Written by Sujal khatiwada on May 4th, 2021
15. Write a PHP script that tests and matches the string: 123-456-7890 and prints a message if there is a successful match.
<?php
$custom_exp = '/[0-9]{3}\-[0-9]{3}\-[0-9]{4}/';
$custom_string = '123-456-7890';
if(preg_match($custom_exp, $custom_string)) {
// Success message
echo "Hurrah!!! the expression matches the string";
} else {
// Prints out this if there is no match
echo "Let's try again to make the correct match.";
}
?>
We are asked to match a string: 123-456-7890. We use the regular expression to generalise the string. This makes it easier for the computer to determine if a match has been found.
If a match is found we use the echo function to output "Hurrah!!! the expression matches the string" . This output is displayed on the browser.
Knowing how the above regular expression works can help us to construct a regular expression that matches a certain phone number pattern like in the form of xxx-xxx-xxxx. This is a real-life use case scenario that many programmers deal with in their day-to-day work.
In this script, we've used a pre-defined PHP function called preg_match() which accepts two arguments, the first is a regular expression and the second one is the string we want to match with the regular expression. If there is a successful match, the function returns 1, and as a result, the code inside the if block executes.
preg_match() returns false if there is any error occurring.
A useful exercise could be to rewrite this code, but instead of using a phone number format use an email address. This will test your knowledge of regular expressions and how to use them effectively.
Written by Sujal khatiwada on May 4th, 2021
16. Write down the regular expression that matches someuser@gmail.com.
/[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]{3}/g
Regular expressions are a very useful resource as a software developer. The syntax can seem very strange and difficult to read... and that's probably because it is!
Most developers do not learn off regular expressions or regex, we use online converters to convert something like an email or common text phrase into regex.
According to the question that has been asked, we need to write a regular expression that matches someuser@gmail.com. We can test this code by using online tools like:
https://regexr.com/
this is a common resource used by developers when they want to use regular expressions.
This question is less about knowing the exact right answer and is more about testing your knowledge in terms of recognising what a regular expression is and knowing some of the online resources available to write your regular expressions.
Written by Sujal khatiwada on May 4th, 2021
17. Mention the difference between require() and require_once() .
The purpose of this question is to determine whether or not you can correctly identify the ideal use cases for either require() or require_once().
Lets first define what the require() function does. The require() function is used to put the data of one PHP file into another PHP file. If there are any errors then the require() function will produce a warning and a fatal error. This error will stop the execution of the script.
The require_once() function is also used to embed code from one PHP file into another; however, the require_once() function checks to see if the file has already been included or not before executing the script. If the file is not found a fatal error is thrown and the program stops. If the file was already included previously this statement will not be included again. This is the key difference between the two functions.
Written by Sujal khatiwada on May 4th, 2021
18. What is the difference between a for and a foreach loop in PHP?
The technical interviewer, when asking this question, is attempting to determine if you know when you can and can not use a for loop or a foreach loop and the reasons why.
The primary difference between a foreach loop is that it processes an instant of each element in a collection in turn. While a for loop can work with any data and is not restricted to collection elements alone.
In summary this means that a for loop can modify a collection which is not possible for a foreach loop as this will cause an error.
<?php
$users= array("tom", "peter", "jack", "michael");
// Using foreach loop
foreach($users as $user) {
echo $user . "<br />";
}
// Using for loop
for($i= 0; $i < count($users); $i++) {
echo $users[$i]."<br />";
}
?>
In the above code, we have used a foreach loop which just outputs each element of an array, but in the case of the for loop, we have 3 expressions.
for(exp1; exp2; exp3)
In this case exp1 is $1=0;
exp2 is $i < count($users)
$exp3 is $i++
We are counting array elements using the count() function. This function is used to determine how many times the loop should iterate or "loop through".
When the loop is initialized using the expression $i=0; the exp2 is then checked, in this case, it's $i < 4, so 0<4 which is true, then the loop body ( code inside of curly brackets {} ) runs.
After that, when the loop body finishes executing, then the exp3 which is $i++ is run, so the value of $i is increased to 1 from 0. So the loop again checks the condition $i < count($users) , so 1 < 4, which is true, so again the loop body runs. The loop continues to run each time until the condition becomes false. It stops iterating if the condition is false.
This outlines the process called iteration. The for loop is said to iterate over the array.
Written by Sujal khatiwada on May 4th, 2021
19. Show/State the two most common string operators being used practically in PHP.
<?php
define("HOST" , "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "database_name");
$connection= mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
// Getting data from the URL, using GET request
$lesson_id = trim($_GET['lesson_id']);
$lesson_id = htmlspecialchars($lesson_id);
$lesson_id = mysqli_real_escape_string($connection, $lesson_id);
$sql = "SELECT * FROM lesson ";
$sql .= "WHERE lesson_id=". $lesson_id; // The place we're using our string operator
$result = mysqli_query($connection, $sql);
?>
Two of the most frequently used operators in PHP are (.) dot, referred to as a concatenation operator and .= which appends the text to the right side of the string in which it is concatenated.
We use . (dot) frequently to concatenate two or more values. You can combine it with a variable name that is defined before using it to form a meaningful SQL query. This is a real life use case of the operator.
Practically, we use .= to combine a multi line query if the query becomes large and we need to break it up so that we can read it and see the query clearly to determine how it's constructed.
It is very important to be familiar with the PHP syntax and to fully understand how to best leverage the operators in real life use cases.
Written by Sujal khatiwada on May 4th, 2021
20. How can you determine the number of rows affected by a query executed using php?
<?php
define("HOST" , "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "db_photos_site");
$connection= mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
$sql= "SELECT * FROM users";
$result = mysqli_query($connection, $sql);
$no_of_rows= mysqli_num_rows($result);
echo "Total No. of rows= ". $no_of_rows;
?>
In the above code, the variable no_of_rows returns the rows affected by the execution of the query. In this example we use SQL (Structure Query Language) to run a query. The query selects everything, denoted by the "*" from the database named "usersâ€.
In the end, we're just echoing out the concatenated string with the no. of rows returned by the mysqli_num_rows function. This then shows how many rows are returned from the SQL query.
Written by Sujal khatiwada on May 4th, 2021
21. Can PHP and Javascript communicate or interact directly?
No, as we know PHP is a server-side scripting language and Javascript is a client-side programming language (technically it's scripting language), so they cannot directly interact with each other.
The interviewer wants to know if you know the difference between a client side and server side programming language.
The client side and server side are sometimes referred to as the front end and back end of a website. As a full stack engineer you will be expected to have a knowledge of both.
The client side of a website refers to the web browser. The server-side of the site refers to where the data is stored and processed.
There are a few ways from which we can interact with PHP and Javascript, such as using AJAX techniques or we can echo out PHP variable values during javascript variable assignment.
Another way is that we can either assign a PHP variable's value from the GET / POST request during javascript's variable assignment.
When interviewing for a full stack engineering role demonstrating your knowledge of how the front end and back end interact is very important in a technical interview.
Written by Sujal khatiwada on May 4th, 2021