Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

101.

How to get last inserted id after insert data from a table in mysql?

Answer»

mysql_insert_id() is USED to get last INSERT ID. It is used after insert data query. It will work when id is ENABLED as AUTO INCREMENT

102.

What is the difference between fopen() and fclose()?

Answer»

 

These both are PHP INBUILT function which is used to open & close a FILE which is pointed file pointer.

S.nofopen()fclose()
1.This method is used to open a file in PHP.This method is used to close a file in PHP. It returns true or false on success or failure.
2.$myfile = fopen("index.php", "r") or die("UNABLE to open file!");$myfile = fopen("index.php", "r");
103.

How to create and destroy cookies in PHP?

Answer»

A cookie is a small FILE that stores on USER's browsers. It is used to store users information. We can create and retrieve cookie values in PHP.

A cookie can be CREATED with the setcookie() FUNCTION in PHP.

Example Create Cookie

$cookie_name = "username";

$cookie_value = "Umesh Singh";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

Update Cookie

$cookie_name = "username";

$cookie_value = "Alex Porter";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");

Delete Cookie

setcookie("username", "", time() - 3600);

104.

What is the difference server side and browser side validation?

Answer»

We NEED to add validation rules while MAKING web forms. It is USED because we need to take inputs from the user in the right way like we need the right email address in the email input field. Some TIME user did not enter the correct address as we aspect. That's why we need validation.

Validations can be applied on the server side or the client side.

Server Side Validation

In the Server Side Validation, the input submitted by the user is being sent to the server and validated using one of the server-side scripting languages like ASP.Net, PHP, etc.

Client Side Validation

In the Client Side Validation, we can PROVIDE a better user experience by responding quickly at the browser level.

105.

How can we make a constant in PHP?

Answer»

With the HELP of DEFINE(), we can MAKE CONSTANTS in PHP.

Example

define('DB_NAME', 'bestInterviewQ')

106.

What is the difference between GET & POST ?

Answer»

These both methods are based on the HTTP method.

GETPOST
The GET method transfers data in the FORM of QUERY_STRING. Using GET it provides a $_GET associative ARRAY to access dataThe post method TRANSFER form data by HTTP Headers. This POST method does not have any RESTRICTIONS on data size to be sent. With POST method data can travel within the form of ASCII as well as BINARY data. Using POST, it provides a $_POST associative array to access data.
107.

What is the latest version of PHP and Mysql?

Answer»

PHP 7.4 is the latest VERSION of PHP and 8.0 is the NEWEST version of Mysql.

Also READ: Latest version PHP 7.4 Released with Advanced Features
108.

What are the advantages of PHP?

Answer»
109.

Write a program to get second highest number in an array using PHP?

Answer»

Example

function displaySecondHighest($arr, $arr_size)
{      
    if ($arr_size < 2)
    {
        echo(" Invalid INPUT ");
        return;
    }  
    $FIRST = $SECOND = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i++)
    {
        if ($arr[$i] > $first)
        {
            $second = $first;
            $first = $arr[$i];
        } else if ($arr[$i] > $second &&
            $arr[$i] != $first)
            $second = $arr[$i];
        }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is " . $second . "\n");
}
 
// Here is your Array
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
displaySecondHighest($arr, $n);
 
OUTPUT:

34

110.

Write a program to get LCM of two numbers using PHP?

Answer»

Here is the program we can use to get LCM of two number using PHP.

Example

// PHP program to find LCM of two numbers

// Recursive function to
// RETURN gcd of a and b
function gcd( $a, $b)
{
      if ($a == 0)
      return $b;
      return gcd($b % $a, $a);
}

// Function to return LCM
// of two numbers
function lcm( $a, $b)
{
      return ($a * $b) / gcd($a, $b);
}

// Driver Code
$a = 15;
$b = 20;
ECHO "LCM of ",$a, " and " ,$b, " is ", lcm($a, $b);

111.

Write a program to swap two numbers using PHP.

Answer»

We have to use the bellow mentioned syntax to swap TWO number using PHP, with or without using the third variable.

Example Without using third variable

<?php ECHO "Before Swapping:";
$a = 1;
$B = 2;
echo "a = $a<br&GT;";
echo "b = $b<br>";

echo "After swapping:<br>";

$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
echo "a = $a<br>";
echo "b = $b";
?>

With using third variable

<?php echo "Before Swapping:<br>";
$a = 1;
$b = 2;
echo "a = $a<br>";
echo "b = $b<br>";

echo "After swapping:<br>";
$temp = $a;
$a = $b;
$b = $temp;

echo "a = $a<br>";
echo "b = $b<br>";
?>

112.

How to send email using php script?

Answer»

First, create a sendEmail.php file in web document root and we have to use the below-mentioned script in it to send email using a PHP script. Change the $to_email with a RECIPIENT email address, $body and $SUBJECT as you require, and $from_email with a sender email address here.

Example

$to_email = "[email PROTECTED]";
$subject = "Simple Email Test via PHP";
$body = "Hi,nn This is test email send by PHP Script";
$headers = "From: [email protected]";
if ( mail($to_email, $subject, $body, $headers)) {
     echo("Email successfully sent to $to_email...");
} else {
     echo("Email SENDING FAILED...");
}

113.

List the different types of Print functions available in PHP?

Answer»

Here are the different types of PRINT FUNCTIONS available in PHP for DEVELOPERS USE:

  • Print() Function
  • Printf() Function
  • Echo() Function
  • Sprintf() Function
  • Print_r() Function
  • Var_dump() Function
114.

What is the role of php.ini file?

Answer»

The php.ini FILE is a default CONFIGURATION file present in APPLICATIONS that require PHP. Developers use it to CONTROL different variables such as file timeouts, resource limits and UPLOAD sizes.

115.

How to remove duplicate values from array using PHP?

Answer»

To remove duplicate VALUES from an array using PHP, we have to use the PHP array_unique() FUNCTION. It removes duplicate values or elements from the array. If our array CONTAINS string keys, then this function will keep the FIRST encountered key for every VALUE and will ignore all other subsequent keys.Example

$var = array("a"=>"best","b"=>"interview","c"=>"question","d"=>"interview");

print_r(array_unique($var));

OUTPUT

Array ( [a] => best [b] => interview [c] => question)

116.

What is the difference between overloading and overriding in PHP?

Answer»
FUNCTION overloadingfunction overriding
The OOPs feature function overloading CONSISTS same function name and the function performs VARIOUS tasks according to the number of arguments.In OOPs feature function overriding, both child and PARENT CLASSES will have the same function name and a different number of arguments.
117.

What is difference between __sleep and __wakeup()?

Answer»
_sleep()_wakeup()
It is USED to return the ARRAY of all the VARIABLES which NEED to be saved.It is used to retrieve all the arrays RETURNED by the _sleep() command.
It is executed before the serialize() command.Is executed before the unserialize() command.
118.

What is difference between drop table and truncate table?

Answer»
Truncate TableDrop-Table
It is a DDL CommandThis command is used to REMOVE a table from the database.
It is executed using a table lock and the WHOLE table is locked while removing all the records.Using this, all the rows, indexes and other privileges SHALL also be removed.
The WHERE clause cannot be used with TRUNCATE.By using this command, no DML triggers shall be fired.
It removes all rows within a table.Once started, this operation cannot be rolled back again.
Minimum logging required in the transaction LOG. Hence, it is more efficient.It is also a DDL command.
This command is used to remove all the data by re-allocating the data pages to store only table data and only using it for recording page deallocations.Removes multiple table data definitions within a database.
119.

What is 'This' key word?

Answer»

In PHP, the “This” keyword is a REFERENCE to a PHP object which has been created by the interpreter for the USER containing an array of variables. If “this” keyword is called inside a normal METHOD WITHIN a normal class, it RETURNS the object to the appropriate method.

120.

What is abstract method and abstract class?

Answer»

In PHP, an abstract class is ONE in which there is at least one abstract method. An abstract method is one that is DECLARED as a method but not implemented in the code as the same.

Example

abstract class PARENTCLASS {
  abstract public function someMethod1();
  abstract public function someMethod2($name, $COLOR);
  abstract public function someMethod3() : string;
}

121.

What is the purpose of break and continue statement?

Answer»

In PHP, DEVELOPERS use the break statement to TERMINATE a BLOCK and GAIN CONTROL out of the loop or switch, whereas the continue statement will not terminate the loop but promotes the loop to go to the next iteration. The break statement can be implemented in both loop (for, while do) and switch statement, but the continue statement can be only implemented in the loop (for, while do) statements.

122.

What is cross site scripting in PHP?

Answer»

Cross-Site Scripting (XSS) is one of the most common and dangerous SECURITY vulnerabilities existing within web applications. It is a MEANS to gain unauthorized access by attacking PHP scripts PRESENT in your web app.

123.

What is design pattern?

Answer»

In PHP, Design patterns are technically a description of communication between objects and classes which are customized in order to solve a common OBSTACLE related to designs in a particular context. Basically, they provide a common REUSABLE solution to everyday programming problems. Design patterns or templates help in speeding up the process of WEB development and can be USED multiple times in different scenarios as REQUIRED.

124.

How to increase the maximum execution time of a script in PHP?

Answer»

There are two ways to increase the maximum EXECUTION time of a script in PHP AVAILABLE as following.

Method 1: Update php.ini file

To complete this process, we have to OPEN the php.ini file and rearrange the max_execution_time (in SECONDS) as per our DESIRED time.

Syntax

max_execution_time = 180 //180 seconds = 3 minutes

Method 2: Update .htaccess file

php_value max_execution_time 300

Method 3: Update your .php file

Here, we have to place the below-mentioned syntax on top of the PHP script.

ini_set('max_execution_time', 300);
ini_set('max_execution_time', 0);

125.

What are default session time and path?

Answer»

The default SESSION time in PHP is 1440 SECONDS or 24 minutes. The default session PATH is a TEMPORARY folder/tmp.

126.

What are getters and setters and why are they important?

Answer»

In PHP, both setters and getters are methods used by DEVELOPERS to obtain or declare variables, especially the private ones.

Why are they important?

They are crucial because these methods ALLOW for a certain LOCATION which will be ABLE to handle before declaring it or while REVERTING it back to the developers.

127.

What is the difference between GROUP BY and ORDER BY?

Answer»
GROUP BYORDER BY
Used for aggregating data in a database.Used for sorting data in a database.
Used to change the form and composition of DataUsed to change the display mode of data.
Attributes within GROUP BY are similarAttributes within ORDER BY are not similar.
Its FUNCTION is to calculate aggregates.Its function is to SORT and arrange in columns.
128.

What is garbage collection in PHP?

Answer»

Garbage collection in PHP refers to allocating and deallocating of space due to repeated USE of a program. Many times, unnecessary space is CONSUMED when a RESOURCE is orphaned after being used. The garbage collector in PHP ENSURES that these kinds of unwanted space consumption are minimized.

129.

What is meant by urlencode and urldocode?

Answer»

In PHP, the urlencode() function is one that can be conveniently used to encode any STRING before ACTUALLY using it as PART of the URL in a query. This function is a very efficient way to pass variables onto the next page. WHEREAS, the urldecode() function is used to decode the above-encoded string into a readable format.

130.

How can we submit a form without a submit button?

Answer»

We can USE document.formname.submit()

131.

What is the IonCube PHP loader?

Answer»

The ionCube Loader is an advanced component used by developers on the SERVER to run ENCODED files. It protects the source code. When our PHP code gets pre-compiled and ENCRYPTED and requires a separate PHP module to LOAD it, ionCube PHP loader will be required at that SCENARIO.

132.

What is the best way to avoid email sent through PHP getting into the spam folder?

Answer»
  • Sending mail USING the PHP mail function with minimum parameters we TEND to should USE headers like MIME-version, Content-type, REPLY address, from address, etc. to avoid this case
  • Did not use CORRECT SMTP mail script like PHPmailer.
  • Should not use website link in mail content.
133.

What is the Apache?

Answer»

Apache HTTP server is the most popular OPEN source web server. Apache has been in use since the YEAR 1995. It powers more WEBSITES than any other product.

134.

How to redirect https to HTTP URL through .htaccess?

Answer»

PLACE this CODE in your htaccess file.

RewriteEngine On

RewriteCond %{HTTPS} on

RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

135.

What is the difference between abstract class and interface in php?

Answer»

Many differences occur between the interface and abstract class in php.

  • Abstract methods can declare with protected, public, private. But in case of Interface methods STATED with the public.
  • Abstract CLASSES can have method stubs, constants, members, and defined processes, but interfaces can only have constants and methods stubs.
  • Abstract classes do not support multiple INHERITANCE but interface support this.
  • Abstract classes can contain constructors, but the interface does not support constructors.

Note: Our PHP logical questions has been created by seasoned PHP experts. It shall help you to ANSWER some of the most frequently ASKED questions during a job interview.

136.

How to write a program to make chess?

Answer»

Example

&LT;table width="100%" cellspacing="0PX" cellpadding="0px" border="XXX2px"&GT;
<?php  
for($row=1;$row<=8;$row++)  
{  
    echo "<tr>";  
    for($column=1;$column<=8;$column++)  
    {
        $total=$row+$column;
        if($total%2==0)
        {  
            echo "<td height='72px' width='72px' bgcolor=#FFFFFF></td>";  
        }  
        else  
        {  
            echo "<td height='72px' width='72px' bgcolor=#000000></td>";  
        }  
    }  
    echo "</tr>";  
}  
?>  
</table>

137.

Write a program to display a table of any given number?

Answer»

Example

function getTableOfGivenNumber($NUMBER) {

   for($i=1 ; $i&LT;=10 ; $i++) {

       echo $i*$number;

   }

}

getTableOfGivenNumber(5);

138.

Write a program to display Reverse of any number?

Answer»

$NUM = 12345;
$revnum = 0;
while ($num &GT; 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}

echo "Reverse number of 12345 is: $revnum";

139.

How can we get the browser properties using PHP?

Answer»

With the HELP of $_SERVER['HTTP_USER_AGENT']

140.

What is a composer?

Answer»

It is an application package manager for the PHP programming language that provides a standard format for MANAGING dependencies of PHP software. The composer is developed by Nils Adermann and Jordi Boggiano, who continue to lead the project. The composer is easy to use, and installation can be done through the command line.

It can be directly downloaded from https://getcomposer.org/download

Using the composer can solve the FOLLOWING problems:
  • Resolution of dependency for PHP PACKAGES
  • To keep all packages updated
  • The solution is autoloading for PHP packages.
46. What is the use of $_SERVER["PHP_SELF"] variable?

It is used to GET the name and path of CURRENT page/file.

141.

How to get a total number of rows available in the table?

Answer»

COUNT(*) is USED to count the NUMBER of ROWS in the table.

SELECT COUNT(*) FROM BestPageTable;

142.

What is the role of a limit in a MySQL query?

Answer»

It is used with the SELECT STATEMENT to restrict the number of rows in the result set. Limit ACCEPTS one or two ARGUMENTS which are OFFSET and count.

The syntax of limit is a

SELECT name, salary FROM employee LIMIT 1, 2

143.

Write a query to find the 2nd highest salary of an employee from the employee table?

Answer»

You can USE this SELECT MAX(SALARY) FROM employee WHERE Salary NOT IN ( SELECT Max(Salary) FROM employee); Query to find the 2nd highest salary of the employee.

144.

What are the final class and final method?

Answer»

Its properties cannot be DECLARED final, only CLASSES and methods may be declared as final. If the class or method DEFINED as final, then it cannot be extended.

Example

class childClassname EXTENDS parentClassname {
    protected $numPages;

    public function __construct($author, $pages) {
       $this->_author = $author;
       $this->numPages = $pages;
    }

    final public function PageCount() {
       return $this->numPages;
    }
}

145.

What is inheritance in PHP? How many types of inheritance supports PHP?

Answer»

Inheritance has THREE types, are given below.

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

But PHP supports only single inheritance, where only ONE class can be DERIVED from a single parent class. We can do the same thing as multiple inheritances by USING interfaces.

Note: Before getting confused with the plethora of PHP interview QUESTIONS for experienced, you need to ensure the basics. This question will help you to understand the core basics of php and make you even more confident enough to jump onto the advanced questions.

146.

What are the different functions in sorting an array?

Answer»

 

The items of an array can be SORTED by various methods.

  • SORT() - it sort arrays in ascending order
  • rsort() - it sort arrays in DESCENDING order
  • asort() - it SORTS ASSOCIATIVE arrays in ascending order, according to the value
  • ksort() - it sort associative arrays in ascending order, according to the key
  • arsort() - it sorts associative arrays in descending order, according to the value
  • krsort() - it sorts associative arrays in descending order, according to the key
147.

How to remove blank spaces from the string?

Answer»

preg_replace('/\s/', '', 'Best Interview Question');

37. What is the difference between Primary Key and Unique key?
Primary KeyUnique Key
It is used to SERVE as a unique identifier for each row WITHIN a table.Used to determine rows that are unique and not a primary key in a table.
It cannot accept NULL values.Unique Key can accept NULL values.
There is the only scope for one primary key in any table.Multiple Unique Keys can be defined within a table.
The primary key creates a CLUSTERED index.Unique Key creates a non-clustered index.

Note: Our PHP interview QUESTIONS for freshers have been selected from a plethora of queries to help you gain valuable insights and boost your career as a PHP Developer.

148.

What is the use of friend function?

Answer»

In PHP, a friend FUNCTION is one non-member function having access to private and protected members WITHIN a class. A friend function has the best USE case when being shared among multiple classes, which can be DECLARED either as member functions within a class or EVEN a global function.

149.

What is the difference between REST and Soap?

Answer»
  • SOAP represent for Simple Object Access Protocol, and REST stands for Representation State Transfer.
  • SOAP is a protocol and Rest is an ARCHITECTURAL style.
  • SOAP permits XML data format only but REST permits different data format such as Plain text, HTML, XML, JSON, etc
  • SOAP REQUIRES more bandwidth and resource than REST so avoid to USE SOAP where bandwidth is minimal.
150.

What is the difference between Apache and Tomcat?

Answer»

Both used to DEPLOY your Java Servlets and JSPs. APACHE is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java TECHNOLOGIES.