Fatskills
Practice. Master. Repeat.
Study Guide: All The Useful PHP Interview Questions & Answers - Part 1
Source: https://www.fatskills.com/php-programming/chapter/all-the-useful-php-interview-questions-answers-part-1

All The Useful PHP Interview Questions & Answers - Part 1

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~29 min read

Q. What is PHP?
PHP or Hypertext Pre-processor is a general purpose programming language written in C and used by developers to create dynamic web applications. PHP Supports both Procedural Programming and Object Oriented Programming.

PHP files generally have extension .php and PHP code is generally written between tags. A hello world program is:

   echo "hello world";
?>

Q. Is PHP case sensitive?
In PHP, variable names are case-sensitive but function names are not case sensitive. If we define function name in lowercase, but calling them in uppercase it will work. So, PHP can be called as partially case-sensitive language.

Q. Is PHP weakly typed language?
Yes, because we don't need to mention the datatype of variables while declaring it. Variables are automatically type casted when the values are inserted in it.

Q. How do we install PHP?
PHP is a cross-platform language and we do have multiple choices to install PHP on different operating systems. We can download PHP from official website and install it or we can make use of popular bundles like XAMPP and WAMP for Windows, LAMP for Linux and MAMP for iOS.

Download WAMP Server.

Q. What is Composer?
Composer is an application-level package manager for the PHP applications that provides a standard system for managing dependencies of different libraries and others. Some of the features of composer are:

dependency resolution for PHP packages
keeping all packages updated
support autoloading out of the box
hooks to execute pre and post commands

To manage dependencies, composer uses composer.json file, which looks like:

{
   "autoload": {
       "psr-0": {
           "": "src/"
       }
   },
   "require": {
       "php": ">=5.3.2"
   },
   "config": {
       "bin-dir": "bin"
   }
}

Q. How to check current PHP version and other information about our system?
We can use function php_info(); inside scripts and using command php -v from command line.

Q. What is interpreter?
PHP interpreter executes command from a PHP script line by line and provides the output to the executer.

Q. Is PHP compiled or interpreted?
Both, PHP is compiled down to an intermediate bytecode that is then interpreted by the runtime engine.

PHP compiler is responsible for:

convert code to a bytecode that can be used by runtime engine.
resolve functions, names and classes names
creating symbol table
then, PHP Interpretor does:

Goes through the bytecode line by line and executes it
Handles runtime exception

Q. Explain datatypes in PHP.

Built-in datatypes in PHP are:

Integer - whole numbers String - alphanumeric text Float - decimal point numbers(also called double) Boolean - represents logical values(TRUE or FALSE) Array - collection of elements having same datatype Object - stores data and information on how to process that data NULL - no value Resource - stores a reference to functions and resources external to PHP

Q. What are rules for naming a variable?
Rules for naming a variable are following −

Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc.

Q. How will you define a constant?
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.

define("MINSIZE", 50);
echo MINSIZE;

Q. What is the purpose of constant() function?
As indicated by the name, this function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.

define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
Only scalar data (boolean, integer, float and string) can be contained in constants.

Q. What are the differences between constants and variables?
There is no need to write a dollar sign ($) before a constant, where as in variable one has to write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the define() function.
Constants may be defined and accessed anywhere without regard to variable scoping rules.
Once the constants have been set, may not be redefined or undefined.

Q. What are the different scopes of variables?
Variable scope is known as its boundary within which it can be visible or accessed from code. In other words, it is the context within which a variable is defined. There are only two scopes available in PHP namely local and global scopes.

Local variables (local scope)
Global variables (special global scope)
Static variables (local scope)
Function parameters (local scope)
When a variable is accessed outside its scope it will cause PHP error undefined variable.

Q. What is string?
A string is a data type used to represent text. It is a set of characters that can also contain spaces and numbers. For example, the word "Bootsity" and the phrase "Bootsity PHP Tutorials" are both strings. To declare strings we can write:

$string = "bootsity";

Q. What is the difference between single quoted string and double quoted string?
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

$variable = "name";
$stringEx = 'My $variable will not print!\\n';
print($stringEx);
$stringEx = "My $variable will print!\\n";
print($stringEx);

Output:

My $variable will not print!
My name will print

Q. How can you convert string into array elements?
explode() function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Syntax:

explode(separator,string,limit);

Q. How can you convert array into strings?
The implode() function returns a string from the elements of an array. The implode() function accept its parameters in either order. The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.

Syntax:

implode(separator,array)

Q. How can you concatenate two or more strings?
To concatenate two string variables together, use the dot (.) operator.

Example:

$string1 = "Hi! i am";
$string2 = "50";
echo $string1 . " " . $string2;
Output:

Hi! i am 50

Q. Differentiate between echo and print().
echo and print are more or less the same. They are both used to output data to the screen.

The differences are:

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 faster than print.

Q. Explain static variables?
The variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.

Example:

function Test() {        
    static $x = 0;        
    echo $x;        
    $x++;        
}            
Test();        
Test();        
Test();    

Output:

0 1 2

Q. What are PHP magic constants?
PHP provides a large number of predefined constants to any script which it runs known as magic constants. PHP magic constants start and end with underscore _

Example:

_LINE_ gives the current line number of the file.

_FILE_ denotes the full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas in older versions it contained relative path under some circumstances.

Q. Why do we need trim() function?
The trim() function removes whitespaces or other predefined characters from either of the sides(beginning and ending) of a string.

Q. Can you count the number of words in a string?
The str_word_count() function counts the number of words in a string.

Example:

echo str_word_count("Hello world!");

Output:

2

Q. How to reverse a string?
strrev() reverses a string.

Example:

echo strrev("Hello World!");
Output:

!dlroW olleH

Q. How to find the position of a specific text in a string?
strpos() returns the position of the first occurrence of a string inside another string (case-sensitive). Also note that string positions start at 0, and not 1.

echo strpos("I love Bootsity, PHP tutorials!","Bootsity");

Output:

7

Q. How can you change cases in a string?
The strtoupper() function converts a string to uppercase and strtolower() function converts a string to lowercase.

Example:

echo strtoupper("Hello WORLD!") . PHP_EOL;
echo strtolower("Hello WORLD!");

Output:

HELLO WORLD!
hello world!

Q. Can you replace a substring?
The built-in function str_replace() replaces some characters in a string (case-sensitive).

Example:

echo str_replace("world","Peter","Hello world!");
Here we have replaced the characters "world" in the string "Hello world!" with "Peter":

Q. Differentiate between str_replace() and str_ireplace().
The str_ireplace() function php is not sensitive rule and will treat "abc","ABC" all combination as a single. The str_ireplace() will be less faster becuse it need to convert to the same case. But the difference will be very little event in a large data. The str_replace() function is a case sensitive which means that it replaces the string that exactly matches the string exactly.

Q. Differentiate between printf() and print().
printf() outputs a formatted string whereas print() outputs one or more strings.

Example:

print "Hello world!";
Output:

Hello world!
Example:

$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.", $number, $str);

Output:

There are 9 million bicycles in Beijing.

Q. Differentiate between strstr() & strchr() functions.
Both the functions finds the first occurrence of a string inside another string so there is no difference. both are alias of each other.

Q. Differentiate between strstr() and stristr().
stristr() and strstr() both finds the first occurrence of a string inside another string where stristr is case-insensitive but strstr() is case sensitive.

Q. Can you encode a string in PHP?
string urlencode (string $str ) function is used to encode a string in PHP. This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Q. Differentiate between strcmp() and strncmp().
Both the functions compare 2 strings(case-sensitive) but strncmp() compares the strings upto N numbers.

Example:

echo strcmp("Hello world!","Hello earth!");
Output:

Q 18 (As the strings are not fully same)
Example:

echo strncmp("Hello world!","Hello earth!",6);

Output:

0 (As the strings are same upto first 6 characters)

Q. Is it possible to remove the HTML tags from data?
The strip_tags() function strips a string from HTML, XML, and PHP tags.

Q. What is the use of gettype() in PHP?
The gettype() is a predefined PHP function which is used to know the datatype of any variable.

Q. What is heredoc and nowdoc?
heredoc and nowdoc allows strings to be defined in more than one line without string concatenation. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

heredoc example:

$name = "Fatskills";

$here_doc = << This is $name website
for Programming Tutorials

EOT;

echo $here_doc;

Output:

This is Fatskills website
for Programming Tutorials

nowdoc example:

$name = "Bootsity";

$here_doc = <<<'EOT'
This is $name website
for ProgrammingTutorials

EOT;

echo $here_doc;
Output:

This is $name website
for PHP, Laravel and Angular Tutorials

Q. Explain if-else statement.
The if statement is a way to make decisions based upon the result of a condition. For example:

$result = 70;
if ($result >= 57) {
    echo "Pass";
} else {
    echo "Fail";
}
Output:

Pass

Q. Explain switch statement with example.
Switch statement works same as if statements. However the difference is that they can check for multiple values. Also, you can do the same with multiple if..else statements, but this is not always the best approach.

$flower = "rose";
switch ($flower) {
    case "rose" : 
        echo $flower." costs $2.50";
        break;
    case "daisy" : 
        echo $flower." costs $1.25";
        break;
    case "orchild" : 
        echo $flower." costs $1.50";
        break;
    default : 
        echo "There is no such flower in our shop";
    break;
}
Output:

rose costs $2.50

Q. Differentiate between switch and if-else statement.
Check the testing expression: An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or string.

switch is better for multi way branching: When compiler compiles a switch statement, it will inspect each of the case constants and create a jump table that it will use for selecting the path of execution depending on the value of the expression. Therefore, if we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.

if-else is better for boolean values: if-else conditional branches are great for variable conditions that result into a boolean, whereas switch statements are great for fixed data values.

Speed: A switch statement might prove to be faster sometimes when there are more if-else in if-else ladder.

Clarity in readability: A switch looks much cleaner when you have to combine cases. if-else are quite vulnerable to errors too. Missing an else statement can land you up in havoc. Adding/removing labels is also easier with a switch and makes your code significantly easier to change and maintain.

Q. What are the different types of operators?
Arithmetic operators
Assignment operators
Logical operators
Comparison operators
Unary operators

Q. Explain arithmetic operators.

Operator -    Use
+    to add numbers
   subtract two numbers
*    to multiply two numbers
/    to divide one number by another
%    to divide two numbers and return the remainder

Q. Explain the assignment operators.
$a = 10;

stores the value 10 in the variable $a

Q. Explain the logical operators.

Operator     - Use
&&
    It returns true, if both expression1 and expression2 are true.
   It returns true, if expression is false.
`    

Q. Explain the unary operators.

Operator -    Use
++    Used to increment the value of an operand by 1.
--    Used to decrement the value of an operand by 1.

Q. Explain the comparison operators.

Operator -    Use
==    Equals
!=    Doesn't equal
>    Is greater than
<    Is less than
>=    Is greater than or equal to
<=    Is less than or equal to
===    Identical (same value and same type)
!==    Not Identical

Q. Differentiate between === and == operators in PHP.
The operator == casts between two different types if they are different, while the === operator performs a typesafe comparison that means it will only return true if both operands have the same type and the same value.

Examples:

1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value

Q. Explain pre and post increment with example.
Operator    Use    Explanation
Pre-increment    ++$a    increments $a by one, then returns $a.
Post-increment    $a++    returns $a, then increments $a by one.
Pre-decrement    --$a    decrements $a by one, then returns $a.
Post-decrement    $a--    returns $a, then decrements $a by one.

Q. What do you mean by operator overloading?
Operator overloading (less commonly known as ad-hoc polymorphism) is a specific case of polymorphism (part of the OO nature of the language) in which some or all operators like +, = or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. Operator overloading is usually only syntactic sugar. It can easily be emulated using function calls.

Q. How many loops are available in PHP?
There are several types of loops in PHP.

while
do-while
for
foreach

Q. Explain while loop with example.
The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of while loop are executed. The test expression is evaluated again. The process goes on until the test expression is false.
When the test expression is false, the while loop is terminated.

Example:

$x = 1; 
while($x <= 5) {
   echo "The number is: $x
";
   $x++;
}
Output:

The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5

Q. Explain do-while loop with example.
The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Example:

$x = 1; 
do {
    echo "The number is: $x
";
    $x++;
} while ($x <= 5);

In the above example, first a variable $x is set to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5.

Q. Explain for loop with example.
for (init counter; test counter; increment counter) {
    code to be executed;
}
loop has 3 arguments.

init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment/decrement counter: Increases/decreases the loop counter value.

Example:

for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x
";

Output:

The number is: 0 
The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 
The number is: 6 
The number is: 7 
The number is: 8 
The number is: 9 
The number is: 10 

Q. Explain foreach loop with example.
The foreach provides an easy way to iterate over associative arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement

foreach (array_expression as $key => $value)
   statement

The first foreach loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

Q. How can you implement an infinite loop in PHP?
This 3 loops can be used to achieve infinite loops in PHP
.

while
do-while
for

 

Examples:

while (1)
//statement`

for (;;;)
//statement`

do {
//statement
}

while (1) {
}
In all the above 3 cases, the loops will execute infinite times as the condition is always true i.e., it returns 1 for while and do-while loops and no ending condition for the for loop.

Q. How can you implement recursion in PHP?
Recursion is the phenomenon of calling a function from within itself.

function factorial($n) {
    // Base case
    if ($n == 0) {
        echo "Base case: \$n = 0. Returning 1...
";
       return 1;
    }
        
    // Recursion
    echo "\$n = $n: Computing $n * factorial(".($n-1).")...
";
    $result = ($n * factorial($n-1));
    echo "Result of $n * factorial(" .($n-1).") = $result. Returning $result...
";
    return $result;
}

echo "The factorial of 5 is: " . factorial(5);

Output:

The factorial of 5 is: 120

Q. Explain break statement with example.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement.

Example:

for ($a = 1; $a < 6; $a++) {
    echo $a;
    if ($a > 3) {
        break;
    }
}
Output:

1234

Q. Explain continue statement with example.
The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.

for ($a = 1; $a < 6; $a++) {
    if ($a == 4) {
        continue;
    }
    echo $a;
}
Output:

1235 (As it skipped 4 due to the continue statement)

Q. Give example of declaration in php.
The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare(ticks=1);

// A function called on each tick event
function tick_handler() {
    echo "tick_handler() called\n";
}

register_tick_function('tick_handler');

$a = 1;
if ($a > 0) {
    $a += 2;
    print($a);
}
Output:

tick_handler() called tick_handler() called tick_handler() called 3tick_handler() called tick_handler() called

Q. What is require in PHP?
Require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

Syntax:

require('somefile.php');

Q. What is an array?
An array is a data structure which is a collection of elements having same datatype stored in a contiguous memory location.

There are 3 types of arrays:

Indexed or Numeric Arrays : An array with a numeric index where values are stored linearly.
Associative Arrays : An array with a string index where instead of linear storage, each value can be assigned a specific key.
Multidimensional Arrays : An array which contains single or multiple array within it and can be accessed via multiple indices.

Example:

$a = array(); // declaration
$cars = array("Volvo", "BMW", "Toyota"); // initialization

Q. How can you print an array in PHP?
Using print_r() method:
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);

Output:

Array
(
   [a] => apple
   [b] => banana
   [c] => Array
       (
           [0] => x
           [1] => y
           [2] => z
       )
)
Using var_dump() method: This method is good at the time of debugging.
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);

Output:

array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    array(3) {
   [0]=>
   string(1) "a"
   [1]=>
   string(1) "b"
   [2]=>
   string(1) "c"
    }
}

Q. What do we mean by the base address of an array?
The base address of an array is the memory location of the first element present in the array i.e., the 0th index element.

Q. What do we mean by keys and values?
In associative arrays, we can use named keys that you assign to them. There are two ways to create an associative array:

// first way -

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

// another method - 
$age['Peter'] = "35"; //Peter, Ben & Joe are keys
$age['Ben'] = "37"; //35, 37 & 43 are values
$age['Joe'] = "43";

Q. What are the keys & values in an indexed array?
Array ( [0] => Hello [1] => world [2] => It's [3] => a [4] => beautiful [5] => day)
The keys of an indexed array are 0, 1, 2 etc(the index values) and values are "Hello", "world", "It's", "beautiful", "day".

Q. How can we convert array into string?
The implode() function returns a string from the elements of an array. The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.

Example:

$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);

Output:

Hello World! Beautiful Day!

Q. How can we convert a string into an array elements?
The explode() function breaks a string into an array.

Syntax:

explode(separator,string,limit)
The "separator" parameter cannot be an empty string.

Example:

$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));

Output:

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

Q. How can we concatenate arrays in PHP?
Using the array_merge() method. The array_merge() function merges one or more arrays into one array.

Example:

$a1 = array("red", "green");
$a2 = array("blue", "yellow");
print_r(array_merge($a1, $a2));

Output:

Array (
   [0] => red 
   [1] => green 
   [2] => blue 
   [3] => yellow
   );

Q. Which function counts all the values of an array?
array_count_values() function is used to count the frequency of values in an array. array_count_values() returns an associative array that has the values of the given array as the keys and frequency as the values.

Example:

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));

Output:

Array
(
   [1] => 2
   [hello] => 2
   [world] => 1
)

Q. How can we check if an element exists in an array?
The in_array() function is used to search for the given string in an array. It returns TRUE if the given string is found in the array, and FALSE otherwise.

Q. Which function inserts an element to the end of an array?
PHP array_push() function is used to insert one or more elements to the end of an array.

Q. What is the use of array_chunk() function?
The array_chunk() function is used to split an array into parts or chunks of new arrays.

Example:

array_chunk(array,size);
The first parameter specifies an array and the second parameter defines the size of each chunk.

Q. Why do we use extract()?
The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

Example:

$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
Output:

$a = Cat; $b = Dog; $c = Horse

Q. What is a function?
A named section of a program that performs a specific task is called a function. In this sense, a function is a type of procedure or routine.

Q. What are the different types of functions?
Built-in functions
User defined functions

Q. Classify function on basis of parameters?
Non parameterized function
Parameterized function

Q. Differentiate between parameterized and non parameterized functions?
Non parameterized functions do not take any parameter at the time of calling.
Parameterized functions take one or more arguments while calling. These are used at run time of the program when output depends on dynamic values given at run time. There are two ways to access the parameterized function
call by value : (here we pass the value directly )
call by reference : (here we pass the address location where the value is stored)

Q. Does PHP support both call by value and call by reference?
Yes.

Q. Explain call by value.
In case of PHP call by value, actual value is not modified if it is modified inside the function.

Example:

function adder($str2) {  
   $str2 .= 'Call By Value';  
}  
$str = 'Hello ';  
adder($str);  
echo $str;  
Output:

Hello

Q. Explain call by reference?
In case of call by reference, actual value is modified if it is modified inside the function. In such case, we need to use & symbol with formal arguments. The & represents reference of the variable.

Example:

function adder(&$str2) {  
   $str2 .= 'Call By Reference';  
}
$str = 'This is ';  
adder($str);  
echo $str;  
Output:

This is Call By Reference

Q. What are the function declaration rules?
A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Q. How can we declare user defined functions?
Using the function keyword.

Example:

function foo($arg_1, $arg_2, /* ..., */ $arg_n) {
   echo "Example function.\n";
   return $retval;
}

Q. What do we mean by actual and formal parameters?
Arguments which are mentioned in the function call is known as the actual arguments. For example:

func1(12, 23);

here 12 and 23 are actual arguments. Actual arguments can be constant, variables, expressions etc.

Arguments which are mentioned in the definition of the function is called formal arguments. Formal arguments are very similar to local variables inside the function. Just like local variables, formal arguments are destroyed when the function ends.

function factorial($n) {
   // write logic here
}
Here n is the formal parameters.

Q. Maximum how many arguments are allowed in a function in PHP?
There is no limit but you can use func_get_args(), func_get_arg() and func_num_args() to avoid writing all the arguments in the function definition.

Q. Explain header()
The header() function sends a raw HTTP header to a client.

Syntax:

header(string,replace,http_response_code)
Here the string specifies the header string to send.

Q. What do we mean by return type of a function?
The return type is similar to a datatype of a function. The common return types are: int, string, float, boolean etc. All the functions donot always need to have a return type.

Q. What is the return type of a function that doesn't return anything?
void which mean nothing.

Q. Do we need to mention the return type of a function explicitly in PHP?
No need to specify return type upon declaration but needs to use return statement within the body of the function.

Q. What is function that can be used to build a function that accepts any number of arguments?
func_num_args() returns the number of arguments passed to the function. func_get_args(void) Gets an array of the function's argument list.

Q. Explain the return statement.
return statement immediately terminates the execution of a function when it is called from within that function. If no parameter is supplied NULL is returned.

Q. Can we use multiple return statements in a function?
Yes but not in consecutive lines. We should then use the statements upon different conditions otherwise it will throw an error.

Example:

function demo() {
   if (condition)
       return expression1;
   else
       return expression2;
}

Q. What is the use of ini_set()?
PHP allows the user to modify some of its settings mentioned in php.ini using ini_set(). This function requires two string arguments. First one is the name of the setting to be modified and the second one is the new value to be assigned to it.

Given line of code will enable the display_error setting for the script if it's disabled.

ini_set('display_errors', '1');

We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.

Q. What is the difference between unlink and unset functions?
unlink() function is useful for file system handling. We use this function when we want to delete the files (physically). Example:

$xx = fopen('sample.html', 'a');
fwrite($xx, '

Hello !!

');
fclose($xx);
unlink('sample.html');
unset() function performs variable management. It makes a variable undefined. Or we can say that unset() changes the value of a given variable to null. Thus, in PHP if a user wants to destroy a variable, it uses unset(). It can remove a single variable, multiple variables, or an element from an array. Let's see a sample code.

 

$val = 200;
echo $val; // Output will be 200
$val1 = unset($val);
echo $val1; // Output will be null
unset($val);  // remove a single variable
unset($val1, $val2, $val3); // remove multiple variables

Q. How ereg() function works?
The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.

Q. How eregi() function works?
eregi() − The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.

Q. What is the purpose of getdate() function?
The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

Q. What is the purpose of date() function?
The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

Q. How will you call member functions of a class?
After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions.

$physics−>setTitle("Physics for High School");
$chemistry−>setTitle("Advanced Chemistry");
$maths−>setTitle("Algebra");
$physics−>setPrice(10);
$chemistry−>setPrice(15);
$maths−>setPrice(7);

Q. How can we display the correct URL of the current webpage?
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; 
gives us the entire URL of the current webpage.

Q. How to get the information about the uploaded file in the receiving script?
$_FILES[$fieldName]['name'] // The Original file name on the browser system. 
$_FILES[$fieldName]['type'] // The file type determined by the browser. 
$_FILES[$fieldName]['size'] // The Number of bytes of the file content. 
$_FILES[$fieldName]['tmp_name'] // The temporary filename  
$_FILES[$fieldName]['error'] // The error code associated with this file upload.

 

Also see:

All The Useful PHP Interview Questions & Answers - Part 2
All The Useful PHP Interview Questions & Answers - Part 3



ADVERTISEMENT