Last Updated On By Khizer Ali
PHP is one of the demanding languages in the market. It is the most popular server-side language. If you are willing to continue your career as a PHP developer, you should have all the essential concepts. In this article, we’ll cover the most frequently asked inte PHP interview questions to help you with your interview.
Table of Contents
PHP is one of the popular scripting side languages which are used for making web applications. PHP stands for Hypertext Preprocessor. It is free of cost so anyone can use it. And it supports multiple databases from which MYSQL is most in demand.
PHP is a loosely typed or weakly typed language. It means that we don’t need to specify what type of information we are going to store in a variable, unlike other languages like Java and C, in which you have to specify the variable’s type. PHP does that automatically for us according to the data which we store.
PHP is a partially case sensitive. It means that the variables are case sensitive, but the names of the functions are not. If you declare a function name in lowercase, you can call that function in uppercase as well. But it is good to assume it as a strictly case-sensitive language and try to use the same letter case for declaration and calling.
It is a framework and a system for reusable PHP components. PEAR stands for “PHP Extension and Application Repository”. The purpose of PEAR is to provide a standard style of code for PHP, a structured library of open-source system for PHP users.
“==” is used for comparing two variables. It returns true if both variables are the same, even if their type is different, whereas “===” is also used to compare variables. But, it strictly checks the data types of the variables.
Both functions are used to add external files in a PHP file. The difference arises if the specified file is not found. include() function will generate a warning and continue the execution of the script. Whereas require() will throw a fatal error and stops further execution.
Both functions are used to add external files into a PHP file. There is only one difference between them. If we use include_once(), then the code which has already been included in the file will not be added again. Means that include_once() include file only once at a time.
GET and POST are the two methods for handling form requests.
GET: When we send data to the server using GET, the data is visible in the URL. It is not a secure way to assign data, so we usually use it to retrieve it. It only provides support for ASCII data, and the length of the URL is limited to 2048 characters.
POST: The parameter of the POST request is not visible in the URL. It is used for sending confidential information to the server. It provides support for ASCII, binary data, and other forms of data as well. There is no length restrictions imposed on POST.
We’ve four types of error.
Fatal Error: This error crashes the program execution and considers a critical error. If we try to call a function that’s never defined, and then the output will be a fatal error.
Parse Error: It is also known as a syntax error. It occurs due to the unclosed quotes, missing parentheses, or missing semicolons.
Warning Error: This error does not stop the execution of the script. It only
warns that there is a problem that might cause more significant issues later on. It can occur if we try to include a file that doesn’t exist in the given path or by passing the wrong number of parameters in a function.
Notice Error: It is similar to the warning error because it doesn’t stop the program execution. It usually occurs when we try to access an undefined variable.
Both functions are used to display something on the screen. But they have the following differences.
We don’t need to mention the data type while declaring a variable in PHP. This is why it is called a loosely typed language. If a variable is declared with an integer value, then it will be of an integer type. Similarly, if a variable is assigned a string value, then the variable will of a string type.
Creating an application from scratch involves a lot of time and hard work. You may have to recreate a function that has already created many times. Frameworks provide us a collection of libraries and functionalities which we can easily use in our application. PHP frameworks offer well-organized and reusable components through which we can quickly start building our app.
Some of the most popular frameworks are:
Laravel: It is the most trending PHP framework. Laravel is a bunch of all the functionality which we need to build a modern PHP application. In Laravel, you have access to functions of authentication, cookies, routing, and session management, which skipped a lot of initial work.
CodeIgniter: It is the lightest weight framework of PHP. Because it is merely of just 2 MB, including its documentation, it is handy in developing dynamic web applications.
Symfony: It is highly flexible. And it is used for large scale projects. But this framework mostly used by experienced developers or programmers.
As the name reflects, the constants are used to define a persistent value. So, we cannot change the value of a constant. To define the constant, we use define() function. And to retrieve the value, we only have to specify its name. A constant must start with a letter or underscore.
The $str is a standard variable which we use to store any data type, like string, float, boolean, char, etc. On the flip side, $$str is known as a reference variable whose name is stored in $str.
<?php
$str = "CodeLeaks";
$refStr = "str";
echo $refStr . "<br>";
echo $$refStr;
?>
str
CodeLeaks
print_r() is a built-in function used to display the provided information like echo and print. But the difference is that it prints the data in a human-readable form.
explode() is used to split a string into an array. On the other hand, implode() is used to create a string by combining the array items.
<?php
$str = "Interview Questions for PHP";
print_r (explode(" ",$str));
echo "<br>";
$strArr = array("Code","Leaks");
echo implode("",$strArr);
?>
We use gettype() function to find the data type of any variable.
<?php
echo gettype(3.14) . "<br>"; //returns double
echo gettype("CodeLeaks") . "<br>"; //returns string
echo gettype(null) . "<br>"; //returns integer
echo gettype(7) . "<br>"; //returns boolean
echo gettype(False) . "<br>"; //returns NULL
?>
The execution time of a script is 30 seconds by default. You can increase it by changing the max_execution_time settings in php.ini file.
If we want to change the settings from coding then place this at the top of our PHP script.
ini_set(‘max_execution_time’, ‘120’); //120 seconds = 2 minutes
ini_set(‘max_execution_time’, ‘0’); // for infinite time of execution
We can also use the below statement if the safe_mode if off.
set_time_limit (120); //120 seconds = 2 minutes
set_time_limit (0); // for infinite time of execution
When we pass a variable then it is called “parsing a variable by value”. In this the main remain variable remain unchanged, while the passed value changes.
<?php
function square($no) {
$no *= $no;
}
$num = 4;
square($num);
echo $num; //returns 4
?>
When a variable is passed by reference, it is called “passing a variable by reference”. Here, the original variable and the given variable share the same memory location. So if one variable changes, the other will change automatically.
<?php
function square(&$no) {
$no *= $no;
}
$num = 4;
square($num);
echo $num; //returns 16
?>
strstr() function searches for the first occurrence of a string inside another string.
echo strstr(“PHP interview questions”, “interview”); //returns “interview questions”
substr() function returns the part of the string based on the starting index and the number of characters. The last parameter is optional, and if it is omitted, then the string from the starting index till the end will be returned.
echo substr(“PHP interview questions”, 4, 9); // returns “interview”
echo substr(“PHP interview questions”, 4); // returns “interview questions”
<?php
$n = 12;
$a = -1;
$b = 1;
for($i = 1; $i <= $n; $i++) {
$c = $a + $b;
echo $c." ";
$a = $b;
$b = $c;
?>
<?php
$str1 = "earth";
$str2 = "heart";
$k = 0;
if(strlen($str1) == strlen($str2)) {
for($i = 0; $i <strlen($str1); $i++) {
for($j = 0; $j <strlen($str2); $j++) {
if($str1[$i] == $str2[$j]) {
$k++;
break;
}
}
}
if ($k == strlen($str2)) {
echo "$str1 and $str2 are anagram";
}
else {
echo "$str1 and $str2 are not anagram";
}
}
else {
echo "$str1 and $str2 are not anagram";
}
?>
2 |
|
|
|
|
4 | 6 |
|
|
|
8 | 10 | 12 |
|
|
14 | 16 | 18 | 20 |
|
22 | 24 | 26 | 28 | 30 |
<?php
$no = 2;
for($i = 0; $i <5; $i++) {
for($j = 0; $j <= $i; $j++) {
echo "$no ";
$no += 2;
}
echo "<br/>";
}
?>
foreach is usually used when we need to iterate through an array that uses key and value pairs.
<?php
$apples = array("Fuji", "McIntosh", "Red Delicious", "Gala", "Jonagold");
foreach($apples as $var) {
echo $var . "<br>";
}
?>
<?php
$apples = array("Fuji", "McIntosh", "Red Delicious", "Gala", "Jonagold");
foreach($apples as $key => $name) {
echo $key. " - " . $name . "<br>";
}
?>
for() loop are usually used when we know how much iterations are required for the loop. It is the most traditional way of writing a loop.
We have three types of arrays available:
Numeric Array: An array having a digital index is known as a Numeric array or indexed array.
Associative Array: Associative arrays are very similar to numeric array in terms of functionality. In this, we can assign names to items of the lists, which are more user-friendly.
Multidimensional array: A multidimensional array in PHP in nothing more than an array, in which each member is itself an array. Each element in the sub-array can also be an array, and so on. This is how the multidimensional array works.
In PHP, we have isset() function available, which returns true if the given variable is defined else return false.
Those functions or methods which start with a double score “__” are known as magic functions or magic methods.
These functions can only be called inside classes.
Some of the most common magic methods are __construct(), __destruct(), __call(), __get(), __set(), etc.
Those items that are declared private will only be accessible inside its class that defines them. Whereas protected variables and methods can be access to a class, which defines them and their child classes.
It exchanges the keys with their associative. In other words, keys become a value, and value becomes keys.
It is known as an error control operator. When we add @ before any statement, if there could be any error, it will be ignored. It is considered a terrible practice because it hides the error and makes the debugging process difficult.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "authentication";
// create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($conn) {
echo "Connecton Open";
}
else
echo "Connection failed";
?>
We can use this query to do the task
$query = “SELECT * FROM STUDENTS”;
$data = mysqli_query($conn,$query);
We can do it in four ways.
mysql is the main extension designed to interact with the database with the help of PHP. But now it has been removed from php version 7 and newer versions.That’s why it is not recommended to use it in new projects.
mysqli is the latest version, which is recommended to use. In mysqli, “i” stands for improved. It also has many features.
mysqli_fetch_object returns result in the form of objects. Fields are accessible like $result-> name, $result -> RollNow.
mysqli_fetch_array returns result in the form of arrays. It’s fields are accessible like $result[name].
Single quote is generally used when we just want to display a string. They just display whatever they are given. They have no special powers to show variables value. We can only use \’ to display a single quote and \\ for display a backslash.
Double quotes can directly add the value of the variable. They can use all the escape sequences.
<?php
$site = "CodeLeaks";
echo 'Welcome to the $site'; //Welcome to the $site
echo "Welcome to the $site"; //Welcome to the CodeLeaks
?>
var_dump display structured information about variable types, size, and values.
<?php
$apples = array("Fuji", "McIntosh", "Red Delicious");
var_dump($apples)
//array(3){ [0]=> string(4)"Fuji" [1]=>string(8) "McIntosh" [2]=>string(13) "Red Delicious" }
?>
print_r displays information in human read able form.
<?php
$apples = array("Fuji", "McIntosh", "Red Delicious");
print_r($apples);
//Array ( [0] => Fuji [1] => McIntosh [2] => Red Delicious )
?>
Spaceship operator has been introduced in PHP7. It compares two expressions and returns 0 if they are equal, returns 1 when the first expression is higher than the second one, one returns -1 if the first expression is less than the second one.
<?php
echo (2 <=> 2); //0
echo (4 <=> 2); //1
echo (2 <=> 4); //-1
?>
mysqli_num_rows() is used, which returns the number of rows.
$query = "SELECT * FROM PACKAGES";
$data = mysqli_query($conn,$query);
$total = mysqli_num_rows($data);
PDO stands for “PHP Data Objects”. The main advantage of using PDO is that it supports uniform access to almost 11 different databases. These databases include MS SQL server, Oracle, PostgreSQL, CUBRID, etc.
$query = "SELECT * FROM STUDENTS";
$stmt = $conn->query($query);
$stmt->execute();
PHP sessions are used to store and pass information from one page to another temporarily. A session creates a file in a temporary directory on the server. The sessions are generally used when we need to authenticate users that only those users can be able to access some particular pages which are registered.
session_start() is a function that is used to create a new session. It starts or resumes the existing session.
session_destroy() is a function which we used to destroy all our session variables.
session_unset() only clears the $_SESSION variable. But the session still exists. It only truncated. It is equivalent to $_SESSION = array();.
session_destroy() destroys the session data, which is saved in the session storage.
$_SESSION is an associative array that stores all the session variables. These variables can be accessed anywhere in the project during the lifetime of the session.
By default, the session timeout in PHP is 24 minutes or 1440 seconds. However, you can change the duration by making changes in php.ini file. To set the session time, go to php.ini file and set the value of gc_maxlifetime in seconds according to your choice.
A cookie is used to identify the user. It is a small file saved on the user’s computer. Each time a computer requests for the same page with a browser, it will send the cookie too.
The main difference between them is session is stored on the server, whereas the cookie is stored on the visitor’s browser. That is why sessions are more secure than cookies because it is stored on the server. Data stored in the cookie can be last for months or years, whereas in session, the data is lost as soon as the web browser is closed.
PHP only supports single inheritance. It means that a class can be extended from only a single parent class using the word “extended”.
Abstract classes can have constants, members, method stubs (methods without a body), and defined methods, whereas interfaces can only have constants and methods stubs.
When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
In this article, we’ve covered PHP technical interview question. I hope these PHP interview questions will help you to boost your confidence level to face any interview. Keep calm and stay positive during your big day because understanding technical concepts isn’t the only thing; your presentation also matters.