PHP Interview Questions - Set 4

PHP Interview Questions

This page contains PHP interview questions and answers.

Q1: Name the programming languages PHP resembles

PHP resembles Perl and C programming language.

Q2: What is the difference between print and echo in PHP?

Both echo and print are language construct and not a function and both are used to print output.

But they have the following differences.

  • echo returns no value while print returns 1
  • echo can take multiple arguments while print can take one argument.

Q3: Write two ways of creating a constant PI and set the value to 3.14 in PHP

We can create constants in the following two ways.

  • Using the define() function
  • Using the const keyword

In the following code we are creating the PI constant using the define function.

define('PI', 3.14);

In the following code we are creating the PI constant using the const keyword.

const PI = 3.14;

Q4: Write PHP code to print the content of an associative array

In the following example we have an associative array $assocArr and we are printing its content using the foreach loop.

$assocArr = array(
  'firstname' => 'Yusuf',
  'lastname' => 'Shakeel',
  'youtube' => 'https://www.youtube.com/yusufshakeel'
);

foreach ($assocArr as $key => $value) {
  echo "<p>{$key} : {$value}</p>";
}

Q5: What is the use of isset function?

We use the isset function to check if a variable is defined and has a value other than NULL.

Q6: What will be the output of the following PHP code?

PHP Code:

$x = null;
isset($x);

Answer: false as $x is set to NULL and isset returns false if value is NULL.

$x = "Hello World";
unset($x);
isset($x);

Answer: false as $x was unset.

Q7: What is the difference between $x and $$x in PHP?

$x is a variable whereas, $$x is a variable of variable.

Example:

$x = 'a';
$$x = 20;
echo $x . ' ' . ${$x} . ' ' . $a;

Output: a 20 20.

In the above code we have a variable $x which is assigned value a.

$$x means $a as $x holds value a. So, we are assigning value 20 to $a.

In the last line we are printing all the value.

Q8: What are magic constants in PHP?

Magic constants are predefined constants which starts and ends with double underscore (__).

Following are some of the magic constants.

  • __LINE__
  • __FUNCTION__
  • __CLASS__
  • __FILE__
  • __METHOD__

Q9: What are the different ways of creating comment in PHP?

We can create single line comments as follows.

  • Using //
  • Using #

We can create multi line comments using /* and */.

Q10: How will you create variable length argument function in PHP?

To create variable length argument function in PHP we have to use three dots like the following.

function foo(...$args) {
  // some code goes here
}

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT