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.

151.

How to check whether a number is Prime or not?

Answer»

Example

FUNCTION IsPrime($n) {

for($X=2; $x<$n; $x++)

{

if($n %$x ==0) {

return 0;

}

}

return 1;

}

$a = IsPrime(3);

if ($a==0)

    echo 'Its not PRIME Number.....'."\n";

else

    echo 'It is Prime Number..'."\n";

152.

What are aggregate functions in MySQL?

Answer»

The aggregate FUNCTION performs a calculation on a set of VALUES and RETURNS a single value. It ignores NULL values when it performs calculation except for the COUNT function.

MySQL provides various aggregate FUNCTIONS that include AVG(), COUNT(), SUM(), MIN(), MAX().

Also Read: What Are The Aggregate Functions in MySQL
153.

How to use Exception handling?

Answer»

Exception handling was introduced in PHP 5 as a new way for the execution of code and what exceptions to make in code in case of a specific error.

There are various keywords of exception handling in PHP like:

Try: This try block consists of the code which could potentially throw an exception. All the code in this try block is EXECUTED UNLESS and until an exception is thrown.

Throw: This throw keyword is used to alert the user of a PHP exception occurrence. The runtime will then use the catch statement to handle the exception.

Catch: This keyword is called only when there is an exception in the try block. The code of catch must be such that the exception thrown is handled efficiently.

Finally: This keyword is used in PHP versions 5.5 and above where the code RUNS only after the try and catch blocks have been executed. The final keyword is useful for situations where a database needs to be closed regardless of the occurrence of an exception and whether it was handled or not.

Note: From the vast number of PHP interview questions, answering this will help you to ALIGN yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

154.

What is the use of cURL()?

Answer»

It is a PHP library and a command line tool that helps us to SEND files and ALSO download data over HTTP and FTP. It also supports PROXIES, and you can TRANSFER data over SSL connections.

Example

Using cURL function module to FETCH the abc.in homepage

$ch = curl_init("https://www.bestinterviewquestion.com/");
$fp = fopen("index.php", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

155.

What is the use of @ in Php?

Answer»

It suppresses error messages. It’s not a good habit to USE @ because it can CAUSE massive debugging headaches because it will EVEN contain critical ERRORS

156.

How can we enable error reporting in PHP?

Answer»

The error_reporting() function defines which errors are reported.We can MODIFY these errors in PHP.ini. You can use these GIVEN function directly in php file.

error_reporting(E_ALL);
ini_set('display_errors', '1');

157.

How to get complete current page URL in PHP?

Answer»

$actual_link = (ISSET($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "HTTP") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

158.

Please explain the difference between $var and $$var?

Answer»

$$VAR is KNOWN as REFERENCE VARIABLE where $var is a NORMAL variable.

159.

How to remove HTML tags from data in PHP?

Answer»

With the help of strip_tags(), we can REMOVE HTML tags from DATA in PHP.

The strip_tags() function strips a STRING from HTML, XML, and PHP tags.

strip_tags(string,allow)

The first parameter is required. It SPECIFIES the string to check.

The second parameter is OPTIONAL. It specifies allowable tags. Mention tags will not be removed

160.

How to get a total number of elements used in the array?

Answer»

We can use the COUNT() or SIZE() FUNCTION to get the number of elements or values in an array in PHP.

Example

$ELEMENT = array("sunday","monday","tuesday");
echo count($element );

echo SIZEOF($element );

161.

What are the difference between array_merge() and array_combine()?

Answer»

1. array_combine(): It is used to creates a NEW array by USING the key of one array as keys and using the value of another array as values.

Example :

$ARRAY1 = array('key1', 'key2', 'key3'); $array2 = array(('umesh', 'SONU', 'deepak'); $new_array = array_combine($array1, $array2); print_r($new_array);

OUTPUT : Array([key1]  => umesh[key2]    => sonu[key2]    =>deepak)

2. array_merge(): It merges one or more than one array such that the value of one array appended at the end of the first array. If the arrays have the same strings key, then the next value OVERRIDES the previous value for that key.

Example :

$array1 = array("one" => "java","two" => "sql"); $array2 = array("one" => "php","three" => "html","four"=>"Me"); $result = array_merge($array1, $array2); print_r($result); Array ( [one] => php [two] => sql [three] => html [four] => Me )

162.

What is the difference between php 5 and php 7?

Answer»

There are differences between php5 and php7.

  • PHP 5 is released 28 August 2014 but PHP 7 released on 3 DECEMBER 2015
  • It is one of the advantages of the NEW PHP 7 is the compelling improvement of performance.
  • Improved ERROR Handling
  • Supports 64-bit windows systems
  • Anonymous Class
  • New Operators

On our website you will find industry's best PHP interview questions for freshers.

Also Read: What is the difference between php5 and php7
163.

What is the difference between file_get_contents() and file_put_contents() in PHP?

Answer»

PHP has multiple FUNCTIONS to HANDLE files operations like read, write, create or delete a file or file contents.

1. file_put_contents():It is used to create a new file.

Syntax :

file_put_contents(file_name, contentstring, flag)

If file_name doesn't exist, the file is created with the contentstring content. ELSE, the existing file is override, unless the FILE_APPEND flag is set.

2. file_get_contents(): It is used to read the contents of a text file.

file_get_contents($filename);

164.

What are the difference between session and cookies in PHP?

Answer»

Session and Cookies both functions are used to store information. But the main difference between a session and a cookie is that in case of session data is stored on the server but cookies stored data on the browsers.

Sessions are more SECURE than cookies because session stored information on SERVERS. We can also turn off Cookies from the browser.

EXAMPLE

session_start();
//session variable
$_SESSION['user'] = 'BestInterviewQuestion.com';
//destroyed the entire sessions
session_destroy();
//Destroyed the session variable "user".
unset($_SESSION['user']);

Example of Cookies

setcookie(name, value, expire, path,domain, secure, httponly);
$cookie_uame = "user";
$cookie_uvalue= "Umesh SINGH";
//set cookies for 1 hour time
setcookie($cookie_uname, $cookie_uvalue, 3600, "/");
//expire cookies
setcookie($cookie_uname,"",-3600);

165.

How to download files from an external server with code in PHP?

Answer»

We can do it by various methods, If you have allow_url_fopen set to true:

  • We can download images or files from an external server  with cURL() But in this case, curl has been enabled on both servers
  • We can also do it by file_put_contents()
Example

$ch = curl_init();
$source = "http://abc.com/logo.jpg";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "/images/newlogo.jpg";
$file = fopen($destination, "w+");
FPUTS($file, $data);
fclose($file);

/*-------This is another way to do it-------*/

$url = 'http://abc.com/logo.jpg';
$img = '/images/flower.jpg';
file_put_contents($img, file_get_contents($url));

18. How many types of errors in PHP?

Primarily PHP supports four types of errors, listed below:-

1. Syntax Error: It will occur if there is a syntax MISTAKE in the script

2. Fatal Error: It will happen if PHP does not understand what you have written. For example, you are calling a function, but that function does not exist. Fatal errors stop the execution of the script.

3. Warning Error: It will occur in FOLLOWING cases to include a missing file or using the incorrect number of parameters in a function.

4. Notice Error: It will happen when we try to access the undefined variable.

Note: The page you are accessing has some of the most basic and complex PHP Interview Questions and Answers. You can download it as a PDF to read it later offline.

166.

How can we upload a file in PHP?

Answer»

For file upload in PHP make sure that the form USES METHOD="POST" and attribute: enctype="multipart/form-data". It specifies that which content-type to use when submitting the form.

Example

$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["MIME"] . ".";
        $uploadOk = 1;
    } ELSE {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

167.

List some string function name in PHP?

Answer»

PHP has LOTS of STRING FUNCTION that helps in DEVELOPMENT. Here are some PHP string functions.

  • nl2br()
  • trim()
  • str_replace()
  • str_word_count()
  • strlen()
  • strpos()
  • strstr()
  • strtolower()
  • STRTOUPPER()
Also Read: PHP Strings Functions
168.

What is the difference between require() and require_once()?

Answer»

require() and require_once() both are used for include PHP files into ANOTHER PHP files. But the difference is with the help of require() we can include the same file MANY TIMES in a single page, but in case of require_once() we can call the same file many times, but PHP includes that file only single time.

Note: From the vast number of php basic interview QUESTIONS, answering this will help you to ALIGN yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

169.

How to make database connection in PHP?

Answer» EXAMPLE

$SERVERNAME = "your hostname";
$USERNAME = "your database username";
$password = "your database password";

// Create connection

$conn = NEW mysqli($servername, $username, $password);

// CHECK connection

if ($conn->connect_error) {
die("Not Connected: " . $conn->connect_error);
}
echo "Connected";

170.

What is the use of the .htaccess file in php?

Answer»

The .HTACCESS file is a type of configuration file for use on web servers running the Apache Web Server SOFTWARE. It is used to alter the configuration of our Apache Server software to ENABLE or disable ADDITIONAL functionality that the Apache Web Server software has to OFFER.

12. List some array functions in PHP?

In PHP array() are the beneficial and essential thing. It allows to access and manipulate with array elements.

List of array() functions in PHP

  • array()
  • count()
  • array_flip()
  • array_key_exists()
  • array_merge()
  • array_pop()
  • array_push()
  • array_unique()
  • implode()
  • explode()
  • in_array()
Also Read: PHP Arrays Functions
171.

How to get IP Address of clients machine?

Answer»

If we USED $_SERVER[‘REMOTE_ADDR’] to get an IP address, but sometimes it will not return the correct value. If the client is connected with the INTERNET through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP, it returns the IP address of the proxy server not of the user’s machine.

So here is a simple FUNCTION in PHP to FIND the real IP address of the user’s machine.

Example

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    ELSEIF (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

172.

What is the difference between MyISAM and InnoDB?

Answer»

There are lots of differences between storage engines. Some are GIVEN below:-

  • MyISAM supports Table-level Locking, but InnoDB supports Row-level Locking
  • MyISAM designed for the need of speed but InnoDB designed for maximum performance when processing a high volume of DATA
  • MyISAM does not support foreign keys, but InnoDB supports foreign keys
  • MyISAM supports full-text search, but InnoDB does not support this
  • MyISAM does not support the transaction, but InnoDB supports transaction
  • You cannot commit and rollback with MyISAM, but You can determine and rollback with InnoDB
  • MyISAM stores its data, tables, and INDEXES in disk space using separate three different files, but InnoDB stores its indexes and tables in a tablespace

Note This is a good question concerning PHP interview questions for experienced.

173.

What are the different MySQL database engines?

Answer»

With PHP 5.6+ "InnoDB" is treated by default DATABASE storage engine. Before that MyISAM DEFAULTED storage engine.

174.

What is the difference between public, protected and private?

Answer»

PHP has three access modifiers such as public, private, and protected.

  • public scope of this variable or function is available from anywhere, other classes, and instances of the object.
  • private scope of this variable or function is available in its class only.
  • protected scope of this variable or function is available in all classes that EXTEND the current class including the parent class.

Note: One of the most TRICKY oops interview questions in php, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry RUN would help you GET that dream job.

175.

What are headers() in PHP?

Answer»

In PHP header() is used to send a raw HTTP header. It must be called before any actual output is sent, either by NORMAL HTML tags, blank lines in a file, or from PHP

Example :

header(string,replace,http_response_code);

1. string: It is the required parameters. It specifies the header string to send.

2. replace: It is OPTIONAL. It indicates whether the header should replace PREVIOUS or add a second header.

3. http_response_code : It is optional. It forces the HTTP response code to the specified value

176.

What is the main difference between require() and include()?

Answer»
require()INCLUDE()
If a required file not found, it will through a fatal error & stops the code executionIf an essential file not found, It will produce a WARNING and EXECUTE the remaining SCRIPTS.
177.

What is the difference between = , == and ===?

Answer»

These all are PHP Operators.

  • = is used to assign VALUE in variables. It is also called ASSIGNMENTS operators.
  • == is used to CHECK if the benefits of the two operands are equal or not.
  • === is used checks the values as well as its data type.
178.

What are magic methods?

Answer»

Magic methods are UNIQUE names, starts with two underscores, which DENOTE means which will be triggered in response to particular PHP events.

The magic methods available in PHP are given below:-
  • __construct()
  • __destruct()
  • __call()
  • __get()
  • __unset()
  • __autoload()
  • __set()
  • __isset()

NOTE: One of the most tricky oops interview questions in php, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry run WOULD help you get that dream job.

179.

What are traits? How is it used in PHP?

Answer»

A trait is a group of various methods that reuse in SINGLE inheritance. A Trait is intended to REDUCE some LIMITATIONS of single inheritance by enabling a developer to reuse sets of processes. We can combine traits and classes to reduce complexity, avoid PROBLEMS typically associated with Mixins and multiple inheritances.

Related Article: How to USE Traits in PHPExample

trait HelloWorld
{
     use Hello, World;
}
class MyWorld
{
     use HelloWorld;
}
$world = new MyWorld();
echo $world->sayHello() . " " . $world->sayWorld(); //Hello World

180.

What is PHP? Why it is used?

Answer»

PHP earlier stood for Personal Home Pages, but now it stands for HYPERTEXT Pre-processor. PHP is a server-side scripting language that is used for building web pages and applications. This language includes MANY Frameworks and CMS for creating LARGE websites.

Even a non-technical person can create web pages or apps using PHP CMS. PHP SUPPORTS various CMS like WordPress, Joomla, Drupal and Frameworks like Laravel, CAKEPHP, Symfony, etc

181.

How to check empty string in php?

Answer»

To check empty STRING in PHP, we can USE the empty() function.

Example

if(empty($VAR1)){
    // TRUE
} else {
   //  False
}

182.

How to find string length in php without strlen?

Answer»
183.

How to convert array to string in php?

Answer»

With the help of implode() function in PHP, we can convert arrays into STRINGS. It returns the string.

implode(separator,array);

Example

$arr = array("BEST", "Interview", "Question");
ECHO implode(" ",$arr);

OUTPUT

Best Interview Question

184.

How to replace multiple characters in a string in php?

Answer»
185.

How to replace string between two characters in php?

Answer»

Here’s a CODE to replace all the text between two specific characters:

Example

FUNCTION replace_all_text_between($str, $start, $end, $replacement) {

    $replacement = $start . $replacement . $end;

    $start = preg_quote($start, '/');
    $end = preg_quote($end, '/');
    $REGEX = "/({$start})(.*?)({$end})/";

    RETURN preg_replace($regex,$replacement,$str);
}

186.

How to read each character of a string in php?

Answer»

For this, the str_split() function can be used. It will CONVERT your string into an array of individual characters where you can enter the START and endpoint of the characters you wish to see.

Example

$str = "Hello";
$arr1 = str_split($str);
print_r($arr1);

Output:

Array
(
[0] => H
[1] => E
[2] => l
[3] => l
[4] => o
)

187.

How to limit string length in php?

Answer»

To limit the characters in a PHP string, use the following code:

if (strlen($STR) > 10)
    $str = substr($str, 0, 6) . '...';

In the above code, if the str value is greater than 10, the OUTPUT will display the final result from 0 to the 6TH character of the said string.

188.

How to find character in string in php?

Answer»
189.

How to convert a string to lowercase in php?

Answer»

You can USE strtolower() to convert any string to lowercase.

Example

strtolower('BEST Interview QUESTIONS');
// OUTPUT: best interview questions

190.

How to get the position of the character in a string in php?

Answer»

To FIND the position of a character inside a string in PHP, USE the strpos() FUNCTION in the following way:
$POS = strpos($string, $CHAR);

191.

How to insert a line break in php string?

Answer»

You can use nl2br() to insert line BREAK in the STRING.

Example

nl2br("Best INTERVIEW \n QUESTIONS");

192.

How to convert a string to uppercase in php?

Answer»

We can use STRTOUPPER() METHOD to CONVERT any string to Uppercase.Example

strtoupper("Best INTERVIEW Questiomns");
// Output: BEST INTERVIEW QUESTIONS

193.

How to replace a text in a string with another text in php?

Answer»

We can USE str_replace() METHOD to REPLACE a TEXT in a STRING with another string.

Example

str_replace("interview","interviews","Best interview questions!");

194.

What is TRIM function in PHP?

Answer»

TRIM() removes all blank spaces or whitespace or other (specified) CHARACTERS from both sides of a string.

$var = “ Best INTERVIEW Questions ”
echo $var;

Types:
  • ltrim() – It removes whitespace/other specified characters from the LEFT side of a string.
  • rtrim() - It removes whitespace/other specified characters from the right side of a string.
Example

$var = “Best Interview Questions”;
ltrim(“Best”, $var);
rtrim(“Questions”, $var);

195.

What is a substring in PHP?

Answer»

SUBSTR() is a substring of PHP. It is an inbuilt function which is USED to extract a PART of the STRING.

196.

How to calculate the length of a string?

Answer»

We can CALCULATE the LENGTH of a string with strlen() FUNCTION in PHP.

$var1 = “This is good interview Question”;
echo strlen($var1);

9. What is the use of strpos in PHP?

strops() method is used to get the position of the first occurrence of a string inside another string.

Example

$mainString = 'Best Interview Question';
echo strpos($mainString, "Interview");
// OUTPUT : 5

197.

What is String in PHP?

Answer»

In PHP, String is a collection of characters. It is one of the data TYPES. We can declare VARIABLE and assign string characters to it and we can DIRECTLY use them with ECHO statement.

Example

$var1 = “This is good INTERVIEW Question”
echo $var1;

198.

What is the difference between print and echo in php?

Answer»

The ECHO and print are basically the same functions, display output data on the SCREEN. HOWEVER, there are some minor differences between the two such as:

EchoPrint
It has no return value.It has a return value of 1, hence can be used in expressions.
It can work with multiple parameters.It can function with only one argument at a time.
It is a bit faster than PrintA bit slower than Print.

Here’s an example of each Echo and Print to clearly demonstrate their proper usage:

Example Echo

echo "PHP is Fun!";

Print

print "PHP coding is Fun!";

199.

How to get string between two characters in php?

Answer»

Suppose we have a

$string = “[Hello there I’m=testing]”

And we want to EXTRACT the string placed between the characters between = and ].

Here’s how to do it using PHP string functions:

EXAMPLE

$str = "[Hello there I’m=testing]";
$from = "=";
$to = "]";

ECHO getStringBetween($str,$from,$to);

FUNCTION getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}

Output:
Testing

200.

How to remove HTML tags from a string using PHP?

Answer»

Here is an example to show how to strip the HTML tags from a PHP string.

Example

$text = '<p>Test paragraph.</p><a href="#fragment">Other text</a>';
ECHO strip_tags($text, '<p><a>');

OUTPUT

Test paragraph.