PHP Interview Questions - Set 2

PHP Interview Questions

This page contains PHP interview questions and answers.

Q1: How will you enable error reporting in PHP?

To enable error reporting we can write the following code error_reporting(E_ALL); and this will start reporting error when the script executes.

Q2: What is the difference between GET and POST request?

We generally use the GET request to fetch data and we use the POST request to insert/save data.

Data sent via GET request becomes a part of the URL and hence not encouraged while sending sensitive data like password. This is not the case with POST request.

With GET we can send ASCII data but with POST we can send even binary data.

GET request can handle some 2048 bytes of data while POST has no such restriction.

Q3: What is the output of the following PHP code?

PHP Code:

$x = [1, 2, 3];
foreach ($x as $n) {
  echo <<<TEMPLATE
<p>{$n}</p>
TEMPLATE;
}

Answer

The above code will print three paragraphs with digit 1, 2 and 3.

Q4: What is the output of the following PHP code?

PHP code:

$x = 10;
$y = &$x;
$y = $y + 10;
echo $x . ' ' . $y;

Answer

The above code will print 20 20.

Note! $y = &$x; implies that $y variable is also referring at the same storage location as variable $x.

So, $y = $y + 10 is similar to $x = $x + 10.

Q5: What is the output of the following PHP code?

PHP code:

$m = 1010;
$n = &$m;
$x = "0$n";
echo $x;

Answer

The above code will print 01010.

Q6: What is the output of the following PHP code?

PHP code

<?php

final class Foo {

  public function greeting() {
    return 'Hello from Foo';
  }

  // some more code goes here
}

class Bar extends Foo {

  public function greeting() {
    return 'Hello from Bar';
  }

  // some code goes here
}

Answer

The above PHP code will not work because class Foo is defined as final class and we can't extend a final class.

Q7: If you have an array how will you find the total number of elements in that array?

To find the total number of elements in an array we use the count() function.

Q8: What is the difference between == and === in PHP?

We use the === operator when we want to check the value and the type. So, === returns true only if both value and type are same.

The == operator just checks the value and not the type.

Q9: What is the output of the following PHP code?

PHP Code

function foo() {
  return 'f' . bar();
}
function bar() {
  return 'o' . fooBar();
}
function fooBar() {
  return 'o';
}
echo foo() . 'bar';

Answer

The above code will print foobar.

Q10: Find the sum of all the digits present in the given string "1 2 3 4 5" using PHP code

For this we can use the explode() function and convert the string into an array and then using the array_sum() function we can add them.

PHP code:

$str = "1 2 3 4 5";
$arr = explode(' ', $str);
$sum = array_sum($arr);
echo $sum;

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT