PHP Interview Questions and Answers for Freshers - PHP Interview

PHP Interview Questions and Answers for Freshers - PHP Interview

 

Welcome to phpinterview.in. If you are looking for php job then you are at right place. We provide mostly asked PHP interview questions and answers . And i am very sure if anyone read the following questions properly. Then any fresher can easily crack the PHP interview. In the PHP interview for fresher there are mostly three rounds HR round (1st), Technical Round (2 nd) and last one again HR round (3rd ) if you clear the interview. In the first round there are very common questions like your brief introduction,why you want to join our company, your current ctc, your expected ctc, why you want to join our company etc.

The technical round is most important part of your interview in which any manager or senior php developer will check your PHP skills by verbal questions or by 2-3 programs with which they check how are your logics. They can ask you php questions, logical programs, sql questions, database questions. And in this article i have add a complete interview questions like PHP, SQL (For more SQL questions you can click here), Database (For more database questions you can click here), Logical Programs (For more programs you can click here)except designing part like HTML, CSS, Jquery. For the designing interview questions please click here. Let’s start the interview.

Que 1:- Write a program to print triangle of stars. For all logical programs please click here.

*
* *
* * *
* * * *
* * * * *

Ans:-

<?php  

for($i=0;$i<=5;$i++){  

for($j=1;$j<=$i;$j++){  

echo "* ";  

}  

echo "<br>";  

}  

?>

Que 2:- Write a program to print pyramid of stars. For all logical programs please click here.


     *
    * *
   * * *
  * * * *
 * * * * *

Ans:-

<?php  

for($i=0;$i<=5;$i++){  

for($k=5;$k>=$i;$k--){  

echo "  ";  

}  

for($j=1;$j<=$i;$j++){  

echo "*  ";  

}  

echo "<br>";  

}

?>

 

Que 3:-Write a program to print reverse triangle of stars ? For all logical programs please click here.


* * * * *
* * * *
* * *
* *
*

Ans:-

<?php  

for($i=0;$i<=5;$i++){  

for($j=5-$i;$j>=1;$j--){  

echo "* ";  

}  

echo "<br>";  

}  

?>

 

Que 4:- Write a program to find out greater element of an array without using any array function. For all logical programs please click here.

Ans:-

<?php

$array = array(10,25,55,784,12,789,852,741,456,264);

$tempGreaterValue = $array[0];

for($i=0; $i<count($array); $i++){

if($array[$i] > $tempGreaterValue){

$tempGreaterValue = $array[$i];

}

}

Echo “grater element of array is ”.$tempGreaterValue;

?>

 

Que 5:- Write a program to swipe two variables without using any third variable. For all logical programs please click here.

 

Ans:-

<?php

$a = 5;

$b = 10;

$b = $a+$b;

$a = $b-$a;

$b = $b-$a;

Echo “Now values of variable a and are ”.$a.”,”.$b;

?>

 

Que 6:- What is PHP ?

Ans:- PHP is a web language based on scripts that allow developers to dynamically create generated web pages.

Que 7:- What is full form of PHP ?

Ans :- PHP stand for Hypertext Preprocessor.

Que 8:- What are the latest version of PHP ?

Ans:- Latest versions of PHP 7.0, 7.1, 7.2.

Que 9:- What are sessions ?

Ans:- Sessions are global variables which are used to store data for some time on server side. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. And session are always specific to current loggedin user and browser (If user is logged in on Google Crome then he wants to use same session on firefox then he can not he has to login on Firefox too)

Que 10:- How to start, set ,read and delete a particular session variable ?

Ans:-

<?php

session_start(); // Start a session.

$_SESSION[‘name’] = “phpinterview.in”; // Session creation

echo $_SESSION[‘name’]; // Print value of session.

unset($_SESSION[‘name’]); // unset any session variable

session_destroy(); // This statement will destroy all sessions.

?>

 

Que 11:- What is sessions default timeout ?

Ans:- It depends on the server configuration Typically the default is 24 minutes (1440 seconds), but you can enhance time

Que 12:- How we can enhance default timeout of session ?

Ans:- server should keep session data for AT LEAST 1 hour. With the below code we can increase session default timeout.

<?php

ini_set('session.gc_maxlifetime', 3600);

?>

Que 13:- I have running session on Google Crome can i use same session on Firefox.

Ans:- No i have to login or create session on firefox as well to use there.

Que 14 :- What are cookies ?

Ans :- Cookies are global variables which are used to store data for some time on user system.

Que 15:- How to set, access and delete cookies ?

Ans:-

<?php

setcookie($cookie_name, $cookie_value, time() + (3600)); //Set cookie

?>

First parameter inside setcookies is a name of cookie with which we will access cookie further, second variable will be value and third parameter will be timeout for cooke when this cookie will expire.

To access cookie value we use $_COOKIE[‘cookie_name’] global variable .

To delete a cookie we will use same function like above but to delete cookie we will use negative time.

<?php

setcookie($cookie_name, $cookie_value, time() - (3600)); //Delete cookie

?>

Que 16:- What is the difference between cookies and sessions ?

Ans:-

Cookies - Your website can be set to place a cookie on a user's computer. That cookie maintains information in the user's machine until the information is deleted by the user. A person may have a username and password to your website. That information can be saved as a cookie on the visitor's computer, so there is no need for him to log in to your website on each visit. Common uses for cookies include authentication, storage of site preferences, and shopping cart items. Although you can store almost any text in a browser cookie, a user can block cookies or delete them at any time. If, for example, your website's shopping cart utilizes cookies, shoppers who block cookies in their browsers can't shop at your website.

Cookies can be disabled or edited by the visitor. Do not use cookies to store sensitive data.

Sessions - A session is server-side information intended to exist only throughout the visitor's interaction with the website.

Only a unique identifier is stored on the client side. This token is passed to the web server when the visitor's browser requests your HTTP address. That token matches your website with the visitor's information while the user is at your site. When the user closes the website, the session ends, and your website loses access to the information.

If you don't need any permanent data, sessions are usually the way to go. They are a little easier to use, and they can be as large as needed, in comparison with cookies, which are relatively small.

Sessions cannot be disabled or edited by the visitor.  

So, if you have a site requiring a login, that information is better served as a cookie, or the user would be forced to log in every time he visits. If you prefer tighter security and the ability to control the data and when it expires, sessions work best.

 

Que 17:- Where cookies get save ?

Ans: -

For Google Crome

C:\Users\<Username>\AppData\Roaming\Microsoft\Windows\Cookies

For Firefox

C:\Users\<Username>\AppData\Local\Mozilla\Firefox\Profiles\some random list of characters.default

Que 18- What are different types of errors in PHP ?

Ans:- Basically there are four types of errors in PHP, which are as follows:

  • Parse Error (Syntax Error)

  • Fatal Error

  • Warning Error

  • Notice Error

1. Parse Errors (syntax errors)

The parse error occurs if there is a syntax mistake in the script; the output is Parse errors. A parse error stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The common reasons for parse errors are as follows:

Common reason of syntax errors are:

  • Unclosed quotes

  • Missing or Extra parentheses

  • Unclosed braces

  • Missing semicolon

Example

 

<?php

echo "Cat";

echo "Dog"

echo "Lion";

?>

2. Fatal Errors

Fatal errors are caused when PHP understands what you've written, however what you're asking it to do can't be done. Fatal errors stop the execution of the script. If you are trying to access the undefined functions, then the output is a fatal error.

Example

<?php

function fun1()

{

echo "Vineet Saini";

}

fun2();

echo "Fatal Error !!";

?>

Warning errors will not stop execution of the script. The main reason for warning errors are to include a missing file or using the incorrect number of parameters in a function.

Example

 

<?php

echo "Warning Error!!";

include ("Welcome.php");

?>

4. Notice Errors

Notice that an error is the same as a warning error i.e. in the notice error execution of the script does not stop. Notice that the error occurs when you try to access the undefined variable, then produce a notice error.

Example

<?php

$a="Vineet kumar saini";

echo "Notice Error !!";

echo $b;

Que 19:- How to avoid errors in PHP ?

Ans:- We can use PHP inbuilt function error_reporting(0) to avoid all errors in PHP file.

Que 20:- What is difference between unset() and unlink() functions ?

Ans:-unset() function is used to unset any variable after unset variable will no more exists. For example

<?php

$a = 10;

unset($a);

Echo $a; // This will print error variable $a not exists.

?>

unlink() function used to delete any file.

Que 21:- What is difference between require() and require_once() ?

Ans:- require(), and require_once() perform the same task except that the second function checks if the PHP script is already included or not before executing it. (same for include_once() and include())

Que 22:- What is difference between include() and require() ?

Ans:- If the function require() cannot access the file then it ends with a fatal error and stop execution. However, the include() function gives a warning, and the PHP script continues to execute.

Que 23:- How to pass any variable one page to another without using session ?

Ans:- We can pass parameter with GET request form one page to another page for example. In the below example we have used variable “var” with value 5 to pass to anotherpage.php and at anotherpage.php we can access it by

<?php

$_REQUEST[‘var’];   ?>

”www.phpinterview.in/anotherpage.php?var=25”"

Que 24:- Write any 10 functions of string ?

Ans:-

Substr() - The substr() function returns a part of a string.

<?php

echo substr("Hello world",6);

//Output will be world;

?>

strtolower() - This function is used to convert uppercase string to lowercase.

<?php

echo strtolower("HELLO");

//Output will be hello;

?>

strtoupper() - This function is used to convert lowercase string to uppercase.

<?php

echo strtoupper("hello");

//Output will be HELLO;

?>

str_word_count() - The PHP str_word_count() function counts the number of words in a string.

<?php

echo str_word_count("Hello world!");

// Output will be 2.

?>

strrev() - The PHP strrev() function reverses a string.

<?php

echo strrev("Hello world!");

// Output will be !dlrow olleH.

?>

strpos() - The PHP strpos() function searches for a specific text within a string.

If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

<?php

echo strpos("Hello world!", "world");

// Output will be 6.

?>

str_replace() - The PHP str_replace() function replaces some characters with some other characters in a string.

<?php

echo str_replace("world", "Dolly", "Hello world!");

// Output will be Hello Dolly!.

?>

trim() - The trim() function removes whitespace and other predefined characters from both sides of a string.

<?php

$a  = ”Hello World ”;

echo  trim($a); // This will remove space from last string and output Hello World

?>

strlen() - The strlen() function returns the length of a string.

<?php

echo strlen("Hello"); // This will output 5.

?>

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

<?php

echo strip_tags("Hello <b>world!</b>"); // In this example, the <b> tag gets stripped. And output will be Hello world!.

?>

 

Que 25:- Write any 10 functions of array ?

Ans:-

array_slice() - The array_slice() function returns selected parts of an array.

<?php

$a=array("red","green","blue","yellow","brown");

print_r(array_slice($a,2));

// Output will be Array ( [0] => blue [1] => yellow [2] => brown )

?>

array_sum() - The array_sum() function returns the sum of all the values in the array.

<?php

$a=array(5,15,25);

echo array_sum($a);

// Output will be 45

?>

arsort() - The arsort() function sorts an associative array in descending order, according to the value.

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(arsort($age));

// Output will be array("Joe"=>"43","Ben"=>"37","Peter"=>"35");

?>

asort() - The asort() function sorts an associative array in ascending order, according to the value.

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(asort($age));

//Output will be array("Peter"=>"35","Ben"=>"37","Joe"=>"43").

?>

count() - The count() function returns the number of elements in an array.

<?php

$cars=array("Volvo","BMW","Toyota");

echo count($cars);

// Output will be 3.

?>

in_array() - The in_array() function searches an array for a specific value.

<?php

$people = array("Peter", "Joe", "Glenn", "Cleveland");

 

if (in_array("Glenn", $people))

 {

 echo "Match found";

 }

else

 {

 echo "Match not found";

 }

// Output will be Match found.

?>

krsort() - The krsort() function sorts an associative array in descending order, according to the key.

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(krsort($age));

// Output will be array("Peter"=>"35","Joe"=>"43","Ben"=>"37")

?>

ksort() - The ksort() function sorts an associative array in ascending order, according to the key.

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(ksort($age));

// Output will be array("Ben"=>"37","Joe"=>"43","Peter"=>"35");

?>

sort() - The sort() function sorts an indexed array in ascending order.

<?php

$cars=array("Volvo","BMW","Toyota");

print_r(sort($cars));

// Output will be array("BMW","Toyota","Volvo")

?>

rsort() - The rsort() function sorts an indexed array in descending order.

<?php

$cars=array("Volvo","BMW","Toyota");

print_r(rsort($cars));

// Output will be array("Volvo","Toyota","BMW")

?>

 

Que 26:- What is constant and how we can define it ?

Ans:- A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

To create a constant, use the define() function.

<?php

define("GREETING", "Welcome to W3Schools.com!");

echo GREETING;

?>

 

Que 27:- What are global variables ?

Ans:- Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

    $GLOBALS

    $_SERVER

    $_REQUEST

    $_POST

    $_GET

    $_FILES

    $_ENV

    $_COOKIE

    $_SESSION

PHP $GLOBALS

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).

PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

<?php

$x = 75;

$y = 25;

 

function addition() {

   $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];

}

 

addition();

echo $z;

?>

In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the function!

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

PHP $_REQUEST

PHP $_REQUEST is used to collect data after submitting an HTML form.

PHP $_POST

PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.

PHP $_GET

PHP $_GET can also be used to collect form data after submitting an HTML form with method="get".

$_GET can also collect data sent in the URL.

Que 28:- What is regex ?

Ans:- regex stand for Regular expressions. Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

 

Que 29:- How to convert a string to array ?

Ans:- By using explode function we can convert any string to array. In the below exmple first parameter is separator which specifies where to break the string

<?php

$str = "Hello world. It's a beautiful day.";

print_r (explode(" ",$str));

// Output will be Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

?>

 

Que 30:- How to convert an array to string ?

Ans :- By using implode function we can convert any array to string.  In implode function first parameter is separator which specifies what to put between the array elements. Default is "" (an empty string)

<?php

$array = array(“how”,”are”,”you”);

Echo implode(“,”,$array);   //Output will be how are you

?>

 

Que 31:- What are scopes of variable ?

Ans:- In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

local

global

static

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable

Que 32:- What are data types ?

Ans:- Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

String

Integer

Float (floating point numbers - also called double)

Boolean

Array

Object

NULL

Resource

 

Que 33:- What are GET and POST requests and what is difference between them ?

Ans:- Suppose we have to sent data browser to server through form if we use GET request then data will be sent in URL. The GET method is restricted to send upto 1024 characters only. If we simply hit any URL this is GET request.

Example :-

http://phpinterview.in?name=test&gender=male&contact=1234567890

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. If we submit form with method POST this is POST request.

Que 34:- What are all HTTP methods in PHP ?

Ans :- HTTP Methods

GET

POST

PUT

HEAD

DELETE

PATCH

GET - in GET method we we sent data through URL. If we hit any URL then this is a GET request.

POST - In post request we sent data through HTTP header. If we submit form with method POST then it is a POST request.

PUT - If we want to edit any information through form then it is PUT request. Suppose we have form where data needs to update then we have entered specified data and hit submit button then it will be PUT request.

HEAD - HEAD is almost identical to GET, but without the response body. In other words, if GET /users returns a list of users, then HEAD /users will make the same request but will not return the list of users. HEAD requests are useful for checking what a GET request will return before actually making a GET request - like before downloading a large file or response body.

DELETE - DELETE request is used in case we put the request to delete any record from database.

Que 35:- How we can check data type of any variable ?

Ans:- Why using var_dump() function we can check the datatype of any variable.

<?php

$a = “phpinterview.in”;

var_dump($a);

// Output will be string(15) "phpinterview.in"

?>

 

Que 36:- Is it possible to extend the execution time of a PHP script?

Ans :- Yes we can extend the default execution time of PHP script by using following code.

Place the following code at top of your script.

<?php

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

?>

Que 37:- How to send mail in PHP ?

Ans:- The mail() function allows you to send emails directly from a script.

Mail function use four parameters first one is reiepent email address(Required), second is subject of email (Required), third one is message body (Required), forth one is headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).

<?php

$to = "somebody@example.com";

$subject = "My subject";

$txt = "Hello world!";

$headers = "From: webmaster@example.com" . "\r\n" .

"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);

?>

Que 38:- How can we get the IP address of the client ?

Ans :- By using $_SERVER['REMOTE_ADDR'] suoerglobal variable we can find out the IP address of client.

Que 39:- What is difference between == and === operator ?

Ans:- == and === both are comparison operator and using to check values are same. == operator return true if values are same even they are of different data type whereas === operator check values are same and they are of same data types else he return false.

<?php

( 123 == ‘123’) // Return true.

( 123 === ‘123’) // Return false.

?>

Que 40:- How can you enable errors in PHP ?

Ans :- Why using error_reporting(E_ALL) in our php script we can enable all PHP errors.

Que 41:- How much data you can sent in GET request ?

Ans :- Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)

Que 42:- In the GET request data sent through URL. But in POST request how data transfer to server ?

Ans :- The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

Que 43:- What is difference between strstr() and stristr() function ?

strstr() – Find first occurrence of a string

Syntax: strstr ($string, string)

Example:

<?php
$email = 'siddharth@yaHoo.com';
$domain_name = strstr($email, 'H');
echo $domain_name; // Output will be Hoo.com.
?>

stristr() – Find first occurrence of a string (Case-insensitive)

Syntax: stristr ($string, string)

Example:

<?php
$email = 'siddharth@yaHoo.com';
$domain_name = stristr($email, 'H');
echo $domain_name; // Output will be harth@yaHoo.com
?>

Que 44:- What are traits ?

Ans:- Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

Que 45:- What are different ways to upload file in PHP ?

Ans :- Why using move_uploaded_file() function we can upload file this function accept two required parameters one is temp path of file and second one destination path with file name.

Que 46:- Is PHP support multiple inheritance ?

Ans :- No php does not support multiple inheritance.

Que 47:- Can we extend final class ?

Ans :- We cannot extend final class and cannot override final declared function.

Que 48:- WHat is difference between echo and print ?

Ans :- The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.

<?php

echo "This ", "string ", "was ", "made ", "with multiple parameters."; // Multiple parameters.

// Output will be

This string was made with multiple parameters.

?>

Que 49:- What are classes ?

Ans:- This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.

<?php
  class phpClass {
     var $var1; // Member Variable
     var $var2 = "constant string";  // Member Variable
     
     function myfunc ($arg1, $arg2) { //Member function
      
     }

  }
?>

Que 50:- What are objects ?

Ans :- An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.

<?php
  class phpClass {
     var $var1; // Member Variable
     var $var2 = "constant string";  // Member Variable
     
     function myfunc ($arg1, $arg2) { //Member function
      
     }

  }

$obj = new phpClass(); // Object creation.
?>

Que 51:- How we can create object of a class ?

Ans :- We can create object of class by using new keyword followed by class name.

<?php
  class phpClass {
     var $var1; // Member Variable
     var $var2 = "constant string";  // Member Variable
     
     function myfunc ($arg1, $arg2) { //Member function
      
     }

  }

$obj = new phpClass(); // Object creation.
?>

Que 52:- What is data type of object ?

Ans :- An object is a data type that not only allows storing data but also information on, how to process that data. An object is a specific instance of a class which serve as templates for objects. Objects are created based on this template via the new keyword.

Every object has properties and methods corresponding to those of its parent class. Every object instance is completely independent, with its own properties and methods, and can thus be manipulated independently of other objects of the same class.

Que 53:- What is inheritance ?

Ans :- Inheritance is one of the most important aspects of OOP. It allows a class to inherit members from another class. Understanding why this is smart without an example can be pretty difficult, so let's start with one of those.

Imagine that you need to represent various types of animals. You could create a Cat class, a Dog class and so on, but you would probably soon realize that these classes would share quite a bit of functionality. On the other hand, there could be stuff that would have to be specific for each animal. For a case like this, inheritance is really great. The idea is to create a base class, in this case called Animal, and then create a child class for each specific animal you need. Another advantage to this approach is that you will every animal you have will come with the same basic functionality that you can always rely on.

<?php

class Animal
{
   public $name;
   
   public function Greet()
   {
       return "Hello, I'm some sort of animal and my name is " . $this->name;
   }
}

class Dog extends Animal
{
   
}

$dog = new Dog();
echo $dog->Greet();

?>

Que 54:- What are abstarct classes ?

Ans :- Abstract classes are special because they can never be instantiated. Instead, you typically inherit a set of base functionality from them in a new class. For that reason, they are commonly used as the base classes in a larger class hierarchy. In the chapter on inheritance, we created an Animal class and then a Dog class to inherit from the Animal class. In your project, you may very well decide that no one should be able to instantiate the Animal class, because it's too unspecific, but instead use a specific class inheriting from it. The Animal class will then serve as a base class for our own little collection of animals.

A method can be marked as abstract as well. As soon as you mark a class function as abstract, you have to define the class as abstract as well - only abstract classes can hold abstract functions. Another consequence is that you don't have to (and can't) write any code for the function - it's a declaration only. You would do this to force anyone inheriting from your abstract class to implement this function and write the proper code for it. If you don't, PHP will throw an error. However, abstract classes can also contain non-abstract methods, which allows you to implement basic functionality in the abstract class. Let's go on with an example.

<?php

abstract class Animal
{
   public $name;
   public $age;
   
   public function Describe()
   {
       return $this->name . ", " . $this->age . " years old";    
   }
   
   abstract public function Greet();
}

?>

Que 55:- What are different scopes of class members (Functions, Variables) ?

Ans :- Class members must be defined as public, private, or protected. If declared using var, the property will be defined as public.

public scope to make that variable/function available from anywhere, other classes and instances of the object.

private scope when you want your variable/function to be visible in its own class only.

protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Que 56:- Why we use $this operator with members of class ?

Ans :- The $this is a keyword which represents the current object or current instance of class. $this is a special self-referencing variable that is used to access properties and methods from within the class.

<?php

class Student {

Public $name;

Public $roll;

function get($a, $b) {

$this->name= $a;

$this->roll= $b;

}

function display() {

echo $this->name."\n";

echo $this->roll."\n";

}

$obj= new Student();

$obj->get("John",38);

$obj->display();

?>

Que 57:- What is :: operator and in what case we use it ?

Ans :- This is scope resolution operator. And we use this operator to access the statich members of class. To access static members of class we have not a need to create object of class.

<?php

Class animals {

Static public function xyz(){

Echo “Hi i am on phpinterview.in”;

}

}

Echo “animals::xyz()” // Output will be “Hi i am on phpinterview.in”.

?>

Que 58: What is encapsulation ?

Ans:- Encapsulation is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation And hiding the essential internal property of that module known as data abstraction.

<?php

class arithmetic {

var $first=1000;

var $second=500;

function add() {

$res=$this->first+$this->second;

echo "Addition = ".$res."<br/>";

}

function sub() {

$res=$this->first-$this->second;

echo "Subtraction = ".$res."<br/>";

}

function mult() {

$res=$this->first*$this->second;

echo "Multiplication = ".$res."<br/>";

}

function div(){

$res=$this->first/$this->second;

echo "Division = ".$res."<br/>";

}

}

$obj= new arithmetic( );

$obj->add( );

$obj->sub( );

$obj->mult( );

$obj->div( );

Output

Addition = 1500

Subtraction = 500

Multiplication = 500000

Division = 2

?>

In the above example

Two properties $first and $second along with the methods add( ), sub( ), mult( ) and div( ) are defined in a single unit i.e in the class arithmetic.

We create the object of class arithmetic. that object called the methods and methods are performed their task with defined properties.

add( ) methods perform addition of two properties $first and $second.

sub( ) methods perform subtraction of two properties $first and $second.

mult( ) methods perform multiplication of two properties $first and $second.

div( ) methods perform division of two properties $first and $second.

Que 59: What is polymorphisom ?

Ans:-  According to the Polymorphismprinciple, methods in different classes that do similar things should have the same name.

According to the Polymorphism principle, methods in different classes that do similar things should have the same name.

Poly means “many” and morphism means property which help us to assign more than one property.

=> Overloading Same method name with different signature, since PHP doesn’t support method overloading concept

=> Overriding When same methods defined in parents and child class with same signature i.e know as method overriding.

Overriding

<?php

class base {

function add($a,$b) {

$res=$a*$b;

echo "Multiplication = ".$res;

}

}

class child extends base {

function add($a,$b){

$res=$a+$b;

echo "Sum  = ".$res;

}

}

$obj= new child();

$obj->add(1000,500);

?>

In the above example

class base have a method add with two signature the same method name with same signature defined in class child also.

But when we call the method add( ) through object of its child, its own method have performed (addition of two number). It means child class add( ) method override its base class method add( ).

 

Que 60:- WHat is use of header function in PHP ?

Ans :- The header() function sends a raw HTTP header to a client.

It is important to notice that header() must be called before any actual output is sent

<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>

Que 61:- How to redirect a page in PHP ?

Ans:- By using header function we can redirect to another page.

<?php

header(location: www.google.com); // This will redirect to www.google.com

?>

Que 62:- How we can stop execution of PHP script ?

Ans:- by using exit function we can stop the execution. Execution run line by line if it gets exit function during execution it stop execution there.

<?php

$a = 10;

$b = 20;

$c = $a+$b;

exit();

Echo $c;

// In the above example execution will stop after addition it will not print variable c.

?>

Que 63:- Why we use isset in PHP ?

Ans :- The isset () function is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset() function return false if testing variable contains a NULL value.

Que 64:- WHat is difference between mysql_fetch_array() ,mysql_fetch_assoc(), mysql_fetch_row() and mysql_fetch_object() ?

Ans :- Mysql_fetch_assoc()

Fetch a result row as an associative array.This function will return a row as an associative array where the column names will be the keys storing corresponding value.

<?php

mysql_connect("localhost", "root", "password");

mysql_select_db("test");

$result = mysql_query("select  * from user");

while ($rows = mysql_fetch_assoc($result))

{

   echo $rows['id'];

   echo "<br>";

   echo $rows['name'];

   echo "<br>";

   echo $rows['email'];

   echo "<br>";

   echo $rows['contactno'];

   echo "<br>";

    echo $rows['addrss'];

   echo "<br>";

echo $rows['posting_date'];

   echo "<br>";

}

Output

2

Anuj

anuj.lpu1@gmail.com

8285703354

New Delhi

2016-03-08 11:06:18

3

Rahul

rahul@gmail.com

2147483647

test address

2016-03-11 10:11:48

?>

Mysql_fetch_array()

Fetch a result row as an associative array, a numeric array and also it fetches by both associative & numeric array.This function will actually return an array with both the contents of mysql_fetch_row and mysql_fetch_assoc merged into one. It will both have numeric and string keys.

<?php

mysql_connect("localhost", "root", "password");

mysql_select_db("test");

$result = mysql_query("select  * from user");

while ($rows = mysql_fetch_arrayc($result))

{

   echo $rows['id'];

   echo "<br>";

   echo $rows['name'];

   echo "<br>";

   echo $rows['email'];

   echo "<br>";

   echo $rows['contactno'];

   echo "<br>";

    echo $rows['addrss'];

   echo "<br>";

echo $rows['posting_date'];

   echo "<br>";

/* Now here both associative array and numeric array will work. */

echo $rows[0];

echo "<br>";

echo $rows[1];

echo "<br>";

echo $rows[2];

echo "<br>";

echo $rows[3];

echo "<br>";

echo $rows[4];

echo "<br>";

echo $rows[5];

echo "<br>";

}

Output

2

Anuj

anuj.lpu1@gmail.com

8285703354

New Delhi

2016-03-08 11:06:18

3

Rahul

rahul@gmail.com

2147483647

test address

2016-03-11 10:11:48

?>

Mysql_fetch_object()

Fetch a result row as an object.

<?php

mysql_connect("localhost", "root", "password");

mysql_select_db("test");

$result = mysql_query("select  * from user");

while ($rows = mysql_fetch_assoc($result))

{

   echo $rows->id;

   echo "<br>";

   echo $rows->name;

   echo "<br>";

   echo $rows->email;

   echo "<br>";

   echo $rows->contactno;

   echo "<br>";

    echo $rows->addrss;

   echo "<br>";

echo $rows->posting_date;

   echo "<br>";

}

?>

Mysql_fetch_row()

Mysql_fetch_row fetch result row an numeric way. This function return a row where the valuew will come in the order as they are defined in the query, and the keys will span from 0 to one less than the number of columns selected.

<?php

mysql_connect("localhost", "root", "password");

mysql_select_db("test");

$result = mysql_query("select * from user");

while ($rows = mysql_fetch_row($result))

{

   echo $rows[0];

   echo "<br>";

   echo $rows[1];

   echo "<br>";

   echo $rows[2];

   echo "<br>";

    echo $rows[3];

   echo "<br>";

    echo $rows[4];

   echo "<br>";

    echo $rows[5];

   echo "<br>";

}

?>

Que 65:- How we can create connection with database ?

Ans :-  We can create connection in three ways.

  • MySQLi (object-oriented)

  • MySQLi (procedural)

  • PDO

MySQLi (object-oriented)

<?php

$servername = "localhost";

$username = "username";

$password = "password";

// Create connection

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

// Check connection

if ($conn->connect_error) {

   die("Connection failed: " . $conn->connect_error);

}

echo "Connected successfully";

?>

MySQLi (procedural)

<?php

$servername = "localhost";

$username = "username";

$password = "password";

// Create connection

$conn = mysqli_connect($servername, $username, $password);

// Check connection

if (!$conn) {

   die("Connection failed: " . mysqli_connect_error());

}

echo "Connected successfully";

?>

PDO

<?php

$servername = "localhost";

$username = "username";

$password = "password";

try {

$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);

   // set the PDO error mode to exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

   echo "Connected successfully";

}

catch(PDOException $e)

{

   echo "Connection failed: " . $e->getMessage();

}

?>

Que 66:- Find nth largest salary from employees table ?

Ans :-  By using following query we can find out the nth largest sallary from employees table.

SELECT sallary FROM `employees` ORDER BY sallary DESC LIMIT 1 OFFSET 0

The above query will find first highest sallary from employees table if you want to find for nth then you have to set OFFSET n-1. Suppose you want to find fifth highest sallary then you will use offset 4

Que 67:- What are triggers in Mysql ?

Ans :- A trigger is a set of actions that are run automatically when a specified change operation (SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table. Triggers are useful for tasks such as enforcing business rules, validating input data, and keeping an audit trail.

Que 68:- What are joins and how many types of join are ?

Ans :- A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables

  • LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table

  • RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table

  • FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

Que 69:- Write a query to INSERT, UPDATE and DELETE data from table ?

Ans:- Suppose we have a table of user and here are some columns name, contact, address, gender, username, password. We want to use INSERT, UPDATE and DELETE query over this table.

INSERT -

INSERT INTO users (name, contact, address, gender, username, password) VALUES (“phpinterview”,”123456789”,”Mohali”, “Male”, “phpinterview”, “1234”);

UPDATE -

UPDATE users SET name = “Sunil”, contact=”000000000”, gender=”Male” WHERE id = 1;

DELETE -

DELETE FROM users WHERE id = 1;

Que 70:- What is difference between where clause and having clause ?

Ans :- The difference between the having and where clause in SQL is that the where clause cannot be used with aggregates, but the having clause can.

The where clause works on row’s data, not on aggregated data.

Suppose we have a table of students and some columns with name marks, name, roll_no etc.

WHERE clause Example :-

SELECT * FROM students WHERE marks > 50

HAVING clause Example :-

SELECT sum(marks) as totalmarks FROM students GROUP BY id HAVING totalmarks > 500

Que 71:- What are types of array ?

Ans :- An array is a special variable, which can hold more than one value at a time.

In PHP, there are three types of arrays:

  • Indexed arrays - Arrays with a numeric index

  • Associative arrays - Arrays with named keys

  • Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

<?php

$cars = array("Volvo", "BMW", "Toyota");

?>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

<?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");  ?>

Multidimensional arrays -

In Multidimensional array elements contain more array.

<?php

$age=array("Peter"=>array(12,25,45,25),"Ben"=>array(57,87,56),"Joe"=>array(5,10,12));

?>

Que 72:- How to find current date and time in PHP ?

Ans :- By using date function we can find the current date and time.

<?php

Echo date(“d-m-Y”); //This will print today date.

Echo date (“d-m-Y h:i:s”) // This will print today’s date and current time.

?>

Que 73:- What is difference between mysql_connect and mysql_pconnect ?

Ans :- - A new connection is established to the database by using mysql_connect, where as mysql_pconnect opens a persistant connection to the database.

- mysql_connect can be used to close the connection, where as mysql_pconnect can not close the connection.

- Database is opened every time when the page is loaded by mysql_connect. Whereas by using mysql_pconnect, database need not be connected every time.

Que 74:- What is difference between $var and $$var ?

Ans :-  $$var uses the value of the variable whose name is the value of $var.

It means $$var is known as reference variable where as $var is normal variable.

It allows you to have a “variable’s variable” – the program can create the variable name the same way it can create any other string.

<?php

$name="Rajeev";

$$name="Sanjeev";

echo $name."<br/>";

echo $$name."<br/>";

echo $Rajeev;

Output

Rajeev

Sanjeev

Sanjeev

?>

Que 75:- What is use of htmlentities function in PHP ?

Ans :- The htmlentities() function converts characters to HTML entities.

<?php

$str = '<a href="http://www.phpinterview.in">Go to phpinterview.in</a>';

echo htmlentities($str);

// output will be (source code)

&lt;a href=&quot; http://www.phpinterview.in &quot;&gt;Go to phpinterview.in&lt;/a&gt;

?>

Que 76:-What is SQL injection and how we can prevent from it ?

Ans :- SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string

What mysql_real_escape_string does is take a string that is going to be used in a MySQL query
and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.

Que 77:- What is PEAR in PHP ?

Ans :- PEAR stands for PHP Extension and Application Repository.The idea behind the Pear was to be able to reuse the existing code and packages, to promote a standard coding style throughout. It also provided a way to install PECL(PHP Extension Community Library) extensions.

In many ways it is similar to 'Composer'(php's de facto package  and dependency manager).Just as Composer downloads and installs packages from  packagist.com . Pear downloads packages from pear.php.net.

Que 78:- What are urlencode and urldecode function ?

Ans :-  

urlencode() -  This PHP function is encodes a string to be used in a query part of a URL.    URL encoding is used when placing text in a query string to avoid it being confused with the URL itself. It is normally used when the browser sends form data to a web server.

Urldecode() - This PHP function is decodes the query part of a URL string. URL encoding is used when placing text in a query string to avoid it being confused with the URL itself. It is normally used when the browser sends form data to a web server.

Que 79:- Who is father of PHP ?

Ans :- Rasmus Lerdorf is the father of php and the year was 1994.

Que 80:- What is recursion in PHP ?

Ans :- PHP also supports recursive function call like C/C++. In such case, we call current function within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack and may cause the termination of script.

<?php   

function display($number) {

if($number<=5){    

echo $number.”,”;    

display($number+1);    }

}      

display(1);  

Output will be 1 , 2, 3, 4, 5  

?>  

Que 81:- What are encryption functions in PHP ?

Ans :- CRYPT() and MD5() are mostly used encryption function in PHP.

<?php

Echo MD5(“String”); //This will print hashed form of string.

?>

The crypt() function returns a hashed string using DES, Blowfish, or MD5 algorithms

Syntax : CRYPT(“String”,”salt”);

The salt parameter is optional. However, crypt() creates a weak password without the salt. Make sure to specify a strong enough salt for better security.

Que 82:- How to upload file in PHP ?

Ans :- Why using move_uploaded_file function we can upload file in PHP.

The move_uploaded_file() function moves an uploaded file to a new location.

This function returns TRUE on success, or FALSE on failure.

Syntax :- move_uploaded_file(file,newloc)

Que 83:- What is difference between PHP 3,PHP 4 and PHP 5 ?

Ans :-  PHP3 is oldest version of PHP development and it was pure procedural language constructive like C

 If we see PHP4, is has some oops concept added like objects and class with new functionality

PHP5 have all major oops functionality has been added along with below thing.

Implementation of exceptions and exception handling

  1. Type hinting which allows you to force the type of a specific argument

  2. Overloading of methods through the __call function

  3. Full constructors and destructors etc through a __constuctor and __destructor function

  4. __autoload function for dynamically including certain include files depending on the class you are trying to create.

Que 84:- How we can find last insert id in table ?

Ans :- By using mysql function mysqli_insert_id() we can retrive the last inserted id in database table.

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

   die("Connection failed: " . mysqli_connect_error());

}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)

VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {

$last_id = mysqli_insert_id($conn);

   echo "New record created successfully. Last inserted ID is: " . $last_id;

} else {

   echo "Error: " . $sql . "<br>" . mysqli_error($conn);

}

mysqli_close($conn);

?>

Que 85:- How we can remove html tags from string ?

Ans :-  The strip_tags() function strips a string from HTML, XML, and PHP tags.

<?php

echo strip_tags("Hello <b><i>world!</i></b>","<b>");

// Output will be Hello world!

?>

Que 86:- What is a conditional statement ended with endif ?

Ans :-  When the original if was followed by: and then the code block without braces.

<?php

$a = 12;

?>

<?php if($a == 12): ?>

<h1>Condition is true.</h1>

<?php endif; ?>

Que 87:- What are different methods of sorting an array ?

Ans :-

sort() - sort arrays in ascending order

rsort() - sort arrays in descending order

asort() - sort associative arrays in ascending order, according to the value

ksort() - sort associative arrays in ascending order, according to the key

arsort() - sort associative arrays in descending order, according to the value

krsort() - sort associative arrays in descending order, according to the key

Que 88:- What is the difference between explode() and implode() function.

Ans :-  The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

The explode() function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

Que 89:- To upload image what attribute of form we use ?

Ans :- To upload a image we use enctype="multipart/form-data".

Que 90 :- What is difference between single quotes and double quotes during assign string value to variable ?

Ans :-   Single quotes :

  1. The simplest way to specify a string is to enclose it in single  quotes. Single quote is generally faster, and everything quoted inside  treated as plain string.

  2. This method  is used when we want the string to be written exactly as it is.

  3. When  string is specified in single quotes PHP will not evaluate it or  interpret escape characters except single quote with backslash (‘) and  backslash(\) which has to be escaped.

Double quote:  

  1. It will display a host of escaped characters (including some regexes), and  variables in the strings will be evaluated.

  2. An important point here is  that you can use curly braces to isolate the name of the variable you want evaluated.

  3. For example let's say you have the variable $type and you what to echo "The $types are" That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.

  4. Use double quotes in PHP to avoid having to use the period to separate code in string.

 

Comments

Damanpreet Kaur

Superb... All things are in one place. Good for freshers who wanna start with basics.

Your Rating: