Interview Questions on PHP

51. What type of inheritance php supports?

PHP supports only single inheritance, where, only one class can be derived from single parent class.

52. What is the difference b/w explode and split?

split() - Split string into array based on  regular expression.
explode() - Split a string based on string

53. What is the use of <?= ?>

To print php variable into  HTML.

54. How to get the session id?

Use session_id() function.
Ex :-   $current_id=session_id();

55. How to get website url in php?

Use  $_SERVER['SERVER_NAME'];

56. How to get date in php?

Use getdate();
Ex :-
<?php
    print_r(getdate());
?>

57. How to check a empty variable?

Use empty ($var );
Ex:-
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}
?>

58. How to trim the variable?

Use trim($var);
Ex :- 
<?php
$test=”  hello world    “;
trim($test);
?>

59. How to use ternary operator?

Syntax:- expression1?expression2:expression3;
Ex :- if($a <= 3) ? echo “a is less than or equal to 3” : echo “$a is greater than 3”;

60. How to print all global variables?

print_r($GLOBALS);

PHP 51 - 60

Interview Questions on PHP

41. How to get a character in particular position of string in php?

Syntax :- $string_name(index_number);
Ex :-
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d

42. How to get index of character/substring of string in php?

Ex :- strops(“main string”,”sub string”);
<?php
echo strpos("I love php, I love php too!","php");
?>

43. How to connect to a database?

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

44. How to execute mysql commands in php?

$sql= “write sql command here ”;
$conn->query($sql);

45. How to assign default values for argument?

Using get :
GET requests can be cached
GET requests remain in the browser history

46. What is the difference b/w get and post?

Using get :
GET requests can be cached
GET requests remain in the browser history

Using post :
POST requests are never cached
POST requests do not remain in the browser history

47. How to access form input values in php?

Use $_POST or $_GET
Ex :-  $_POST[‘form_input_name’];

48. How to know total number of elements in array?

Use count();
Ex :- 
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
?>

49. How to encrypt to md5 in php?

Use md5 function
Ex :-
<?php
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

50. How to upload file in php?

Syntax :-  move_uploaded_file ( string $filename , string $destination );
Ex :- 
<?php
        $uploads_dir = '/uploads';
        $tmp_name = $_FILES["fileToUpload"]["tmp_name"];
        move_uploaded_file($tmp_name, "$uploads_dir/filename ");
?>

PHP 41 - 50

Interview Questions on PHP

31. Explain function overriding?

Overriding :- The process of replacing parent class function with child class function is nothing but function overriding.
Ex :-
<?php
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"
?>

32. What is the difference b/w method overloading and method overriding?

In Over Loading Signature must be different.
In OverRiding signature must be same.

33. How to get another website output into a variable?

Use below function :-
$var_name = file_get_contents('http://www.websitename.com');

34. How to open file in write mode?

$myfile = fopen("webdictionary.txt", "w");

35. What is diff b/w r+,w+ and a+ modes?

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

36. Write a php code to copy one file contents to another file?

copy ( string $source_file_path , string $dest+file_path ).
Ex :-
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

37. How to write key & values in php?

Example code :-
$array = array(
    'key1' => 'value1',
    'key2' => 'value2' ,
    'key3' => 'value3' ,
    'key4' => 'value4',
    'key5' => 'value5');

38. What is the difference b/w include and require_once?

a. difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute.
b. require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error.

39. How to reverse a string in php?

Syntax :-  strrev( string $string );
Ex :- 
<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

40. How to get substring in php?

Syntax :-  substr( string $string );
Ex :-
<?php
echo substr("Hello world",6);
?>

PHP 31 - 40

Interview Questions on PHP

21. How to create an array in php?

Ex :- $array_name = array("value1", " value2", " value3");

22. Explain foreach statement in php?

Syntax  :- 
foreach (array_expression as $value)
    statement
Ex :-
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

23. How to write “ in string which is enclosed with in double quotes?

Use \
Ex :- “this is \“Text\” enclosed in double queotes”.

24. What is pass by value and pass by reference?

Pass By value :-
Pass variables as arguments to the function.
Syntax :-
<?php
function foo($var)
{
    $var++;
}
$a=5;
foo($a);
// $a is 6 here
?>

Passing by Reference :-
You can pass a variable by reference to a function so the function can modify the variable. 
Syntax:
<?php
function foo(&$var)
{
    $var++;
}
$a=5;
foo($a);
// $a is 6 here
?>

25. How to write Exception handlings in php?

Syntax :-
try {
    // Code goes here
}
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}
Ex: -
try {
  checkNum(2);
  //If the exception is thrown, this text will not be shown
  echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}

26. If we write return in both try and finally block which block will it execute?

finally

27. How to declare constant values in php?

1. If we want to declare out side of class use
       define(const_name', 'value');  
2. If we want to write inside class then use
       const  const_name = value;

28. How to declare global variable in php?

Declare those varibles outside function.
Ex :- 
<?php
$a = 1; /* global scope */ 
function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 
test();
?>

29. How to write and execute constructor in php?

Syntax :-
void __construct ([ mixed $args = "" [, $... ]] )
Ex :-
<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}
?>
Constructors will be executed at the time of creation of objects.

30. Explian function overloading?

Function Over Loading :- Function Overloading happens if multiple functions exist with same name but different parameters.
Ex :- 
class Foo {
   function myFoo() {
      return "Foo";
   }
  function myFoo($a) {
      return "Foo with one arg";
   }
}
$foo = new Foo;
echo($foo->myFoo());    //"Foo"
echo($foo->myFoo("a")); //

PHP 21 - 30

Interview Questions on PHP

11. How to create session variable?

Ex :-  
session_start();
$_SESSION["session_var1"] = "value1";
$_SESSION["session_var2"] = " value2";

12. How to destroy the session variable?

unset ($_SESSION['varname']);

13. What is the difference between cookie and session variables?

Cookies will be created and stored in browser.
Sessions will be created by Server and maintained bybrowser.

14. Which one is best to use cookie or session variable?

Sessions
Reason:-
Sessions are stored on the server, which means clients do not have access to the information you store about them. You do not need to send the data for each request.
On the other hand, Cookies maintained in browser and data stored in Cookies is transmitted in full with each page request.

15. How to create object for a class?

By using new operator.
Ex :- 
Class Foo{
   //data members
}
$foo = new Foo;

16. How to call a function of a class in php?

By using -> operator
Ex :- 
Class Foo{
   //data members
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }
}
$foo = new Foo;
$foo->newTest();

17. How to include other php file code?

By using include
Ex :- 
<?php
include otherfilename.php';
?>

18. What are the most popular php frame works?

• Laravel
• CakePHP
• Zend Framework
• Phalcon
• Slim
• Yii

19. What is the difference b/w echo and print statement?

echo can take multiple parameters (although such usage is rare) while 
print can take one argument.

20. How to concat strings in php?

By using . operator
Ex :- 
<?php
echo "thr"."ee";           //prints the string "three"
echo "twe" . "lve";        //prints the string "twelve"
echo 1 . 2;                //prints the string "12"
echo 1.2;                  //prints the number 1.2
echo 1+2;                  //prints the number 3
?>

PHP 11-20

Interview Questions on PHP

1. What is PHP?

PHP(Hypertext Pre Processor) :-  PHP is server side programming language that is used to develop the web applications and can be easily embed with HTML code.

2. How to write HTML code in PHP?

Two ways.
1. By using echo :-  
Ex :-  
<?php 
 echo “
This text visible in browser
”; ?> 2. Write html code out side php context :- Ex :- <?php // php codde goes here ?> <!--write HTML code here --> <div> text message </div> <?php //php code goes here ?>

3. How to declare and initialize variables?

variable starts with the $ sign, followed by the name of the variable.
Syntax :- $variable_name = value;
Ex :-  $name = “ramesh”;

4. What is the difference b/w $var and $$var?

Below example describes difference b/w $ and $$
Ex :- 
<?php
    $var1 = msg;
    $$var1 = “value1”;  // equalent to $msg = “value1”;
    echo $msg;
 ?>
o/p :- value1

5. How to write comments in PHP?

1. Single line comment :- starts with // followed by comments.
Ex :- 
<?php 
      //Commented lines
?>
2. Multi line comment :-
Multiline comments starts with /* and ends with */
Ex :- 
<?php
/* Comment line 1
     Comment line 2
     Comment line 3
*/
?>

6. How to redirect to another web page in php?

Use header()
Ex :- 
<?php    
      header('Location: /directory/mypage.php');    
?>

7. What is cookie?

Cookie :-  Cookie is a variable that stores data in browser to manage web applications.

8. How to create cookie?

Create Cookie :-  use setcookie()
Synatax :- setcookie($cookie_name, $cookie_value,expirytime);

Ex :-  setcookie($cookie1, “456”, time() + (86400 * 30), "/");
here "/" means that the cookie is available in entire website.

9. How to destroy the cookie?

Ex :- 
unset($_COOKIE['cookie_name']);
setcookie('cookie_name', null, -1, '/');

10. What is session variable?

Session Variable :-
Session variable is used to store values to maintain the web applications.
Session variable is created by created and maintained by browser.

PHP 1-10