PHP Interview Questions


1) What is PHP?
PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.

2) What is PEAR in PHP?
PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries.

3) PHP string function
implode() = array into string
explode() = string into array
echo()    = Outputs one or more strings
md5()     = Calculates the MD5 hash of a string
print()   = Outputs one or more strings
printf()  = Outputs a formatted string
strlen()  = Returns the length of a string
ucfirst() = Converts the first character of a string to uppercase
ucwords() = Converts the first character of each word in a string to uppercase
strip_tags() = Remove HTML Tage in php

4) PHP Array Functions
array()   = Creates an array
array_fill() = Fills an array with values
array_fill_keys() = Fills an array with values, specifying keys
array_filter() = Filters the values of an array using a callback function
array_flip() = Flips/Exchanges all keys with their associated values in an array
array_merge() = Merges one or more arrays into one array
array_push() = Inserts one or more elements to the end of an array
array_pop() = Deletes the last element of an array
array_search()  = Searches an array for a given value and returns the key
count() = Returns the number of elements in an array
range() = Creates an array containing a range of elements

5) Basically four types of errors in PHP
Parse Error (Syntax Error) = if there is a syntax mistake in the script; the output is Parse errors. A parse error  stops the execution of the script.

Fatal Error = Fatal errors stop the execution of the script. If you are trying to access the undefined functions,  then the output is a fatal error.

Warning Error = Warning errors will not stop the execution of the script.

Notice Error = Notice that the error occurs when you try to access the undefined variable, then produce a notice  error.

6) overloading = if any class have multiple functions with same name but different arguement is called overloading.
class Addition {
  function compute($first, $second) {
    return $first+$second;
  }

  function compute($first, $second, $third) {
    return $first+$second+$third;
  }
}

7) overriding  = parrent and child class in funcation same name but out put for child class.
Defining function in the derived calss with the same name in the parent class is called function overriding.

class Foo {
   function myFoo() {
      return "Foo";
   }
}

class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}

$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"

8) require() & included()

require()  = statement will generate a fatal error and stops the script execution.

included() = the file to be included can't be found and  script execution to continue

9) What is the difference between "echo" and "print" in PHP?

echo :  Echo can output one or more string
Echo is faster than print because it does not return any value.

print : print can only output one string and always returns 1.

10) PHP $ and $$ Variables
$ = The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.

$$ = The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;

11) How many data types are there in PHP?
Scalar types , Compound types , Special types

12) What are the different loops in PHP?
For, while, do-while and for each.

while — loops through a block of code as long as the condition specified evaluates to true.
do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
for — loops through a block of code until the counter reaches a specified number.
foreach — loops through a block of code for each element in an array.

13) What does isset() function?
The isset() function checks if the variable is defined and not null.

14) List some of the features of PHP7.
Scalar type declarations
Return type declarations
Null coalescing operator (??)
Spaceship operator
Constant arrays using define()
Anonymous classes
Closure::call method
Group use declaration
Generator return expressions
Generator delegation
Space ship operator

15) What is the array in PHP?
An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and values. It saves the collection of the data type.

16) How many types of array are there in PHP?
 - Indexed array: an array with a numeric key.

 - Associative array: an array where each key has its specific value.

 - Multidimensional array: an array containing one or more arrays within itself.

17) How can you retrieve a cookie value?
echo $_COOKIE ["user"];

18) What is the difference between session and cookie?
The main difference between session and cookie is that cookies are stored on user's computer in the text file format while sessions are stored on the server side.

Cookies can't hold multiple variables, on the other hand, Session can hold multiple variables.

You can manually set an expiry for a cookie, while session only remains active as long as browser is open.

19) How to upload file in PHP?
move_uploaded_file ( string $filename , string $destination )

20) How to download file in PHP?
int readfile ( string $filename )

21) What is OOPS?
In Programming Language data is logically represent in the form of class and physically represent form of object is callled oops. 

22) What is polymorphism? When we use it?

Ploymophism is the process of one form into many form in object oriented programming language.
polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

23) What is abstract and interface difference?
Abstract classes are those classes which can not be directly initialized.or in other word we can say that you can not create object of abstract classes.
abstract classes always  create for inheritance purpose.you can only inherit abstract calss in childs class.

Interface can have only abstract methods.
Interface supports multiple inheritance.
Interface can't provide the implementation of abstract class.
The interface keyword is used to declare interface.

24) What is Object?
object" refers to a particular instance of a class where the object can be a combination of variables, functions, and data structures.its run time entities called object.

23) What is Class?
Class is collection of data member and member funtions by the three access specifiers private, protected or public

->private = A private constant, property or method can only be accessed from within the class that defines it.
->protected = A protected constant, property or method can only be accessed from within the class that defines it,   or a descendant of that class.
->public = A public constant, property or method can be accessed from anywhere.

24) what is inheritance?
 A derived (Child) class inherits property of base class is called inheritance.

25) What is Virtual keyword?
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class

26) what is abstract class?
Abstract classes are those classes which can not be directly initialized.Or in other word we can say that you can not create object of abstract classes.Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract

27) What is an Interface?
An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

28) What is pure virtual function?
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0. Here is the syntax for a pure virtual function.
virtual void f() = 0;

29) Difference Between Static Binding And Dynamic Binding.
Static binding is done at compile time when a function is called in order to match it with the definition.

Dynamic binding is at run time where we can specify that the compiler matches a function call with the correct function definition at run time.

30) fetch_assoc() , fetch_array() , fetch_object() , fetch_row()

fetch_assoc() :  This gets you an associative array of data.Fieldnames returned (only fields name like ['id'],['name'])

fetch_array() : This returns a combination array of associative elements as well as data with numerical index.(both [0],[1] and ['id'],['name'])

fetch_object() : Returns an object with properties that correspond to the fetched row.Fieldnames returned from this function

fetch_row() : It return values as numeric array [only index value[o],[1]...]

31) What is unset() and unlink() in PHP?

- The unset() function destroys a given variable.and Makes varialbe undefined

- unlink() is used to delete the files.

32) trim() , ltrim() , rtrim()
- trim() - function removes whitespace and other predefined characters from both sides of a string.

- ltrim() - Removes whitespace or other predefined characters from the left side of a string

- rtrim() - Removes whitespace or other predefined characters from the right side of a string

34 ) What is SQL Injection ? How it works ?

- An SQL Injection can destroy your database

- SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.(Hacking websites)

35) Difference between while and do while

- while loop entry controll loop statement
- do while exit control loop statement

36) What is the difference between =, == and === in PHP?

x=y : The left operand gets set to the value of the expression on the right

x==y : $x == $y Returns true if $x is equal to $y($x=10,$y=10)

$x === $y : Returns true if $x is equal to $y, and they are of the same type

37) __construct():
initialize the object and its properties by assigning values.

38) __destruct():
destroying the object or clean up resources here

39) Difference explode and implode (both string functions)

-implode-> it convert array into String

example

$arr=array("one","two","three","four");
$str=(implode(",",$arr));
echo $str;

o/p one,two,three,four

-explode->it convert string into array

example

$arr=("Hello World How Are You");
print_r (explode(" ",$arr));

$arr=("one","two","three","four");
$str=explode(",",$arr);
echo $str;
print_r($str);
[0]=>one
[1]=>two
[2]=>three
[3]=>four

40) what is difference between function and method

-A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value).

-A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
 too ading


41) How to count days between two dates in PHP?

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

OR

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);


42) Swapping Using Third Variable

$a = 45;
$b = 78;

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

43) Swapping Without using Third Variable

$a=2;
$b=3;

$a=$a+$b;  // 2 + 3 = 5
$b=$a-$b;  // 5 - 3 = 2
$a=$a-$b;  // 5 - 2 = 3
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";


44) how to find length of string without using string function in php

<?php

$s = 'dixit';
$i=0;
while ($s[$i] != '') {
  $i++;
}
print $i;

?>

45) What is jQuery?
jQuery is a fast, lightweight, feature-rich client-side JavaScript library. It is cross-platform and supports different types of browsers. It has provided a much-needed boost to JavaScript. Before jQuery, JavaScript codes were lengthy and bigger, even for smaller functions. It makes a website more interactive and attractive.

46) What is the difference between JavaScript and jQuery?

The simple difference is that JavaScript is a language while jQuery is a built-in library built for JavaScript. jQuery simplifies the use of JavaScript language.

47) Hook Points
In CodeIgniter, hooks are events which can be called before and after the execution of a program. It allows executing a script with specific path in the CodeIgniter execution process without modifying the core files.


The list of hook points is shown below.
pre_system
It is called much before the system execution. Only benchmark and hook class have been loaded at this point.
pre_controller
It is called immediately prior to your controller being called. At this point all the classes, security checks and routing have been done.
post_controller_constructo
It is called immediately after your controller is started, but before any method call.
post_controller
It is called immediately after your controller is completely executed.
display_override
It is used to send the final page at the end of file execution.
cache_override
It enables you to call your own function in the output class.
post_system
It is called after the final page is sent to the browser at the end of the system execution.

48) What are Traits?
Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.

It’s important that a developer knows the powerful features of the language (s)he is working on, and Trait is one of such features.

Post a Comment

0 Comments