0% found this document useful (1 vote)
1K views73 pages

PHP Mcqs

Uploaded by

Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
1K views73 pages

PHP Mcqs

Uploaded by

Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

1. What does PHP stand for?

i) Personal Home Page


ii) Hypertext Preprocessor
iii) Pretext Hypertext Processor
iv) Preprocessor Home Page

a) Both i) and iii)


b) Both ii) and iv)
c) Only ii)
d) Both i) and ii)

Answer: d
Explanation: PHP previously stood for Personal Home Page now stands for Hypertext
Preprocessor.

2. PHP files have a default file extension of_______


a) .html
b) .xml
c) .php
d) .ph

Answer: c
Explanation: To run a php file on the server, it should be saved as AnyName.php
advertisement

3. What should be the correct syntax to write a PHP code?


a) < php >
b) < ? php ?>
c) <? ?>
d) <?php ?>

Answer: c
Explanation: Every section of PHP code starts and ends by turning on and off PHP tags to let
the server know that it needs to execute the PHP in between them.

4. Which of the following is/are a PHP code editor?

i) Notepad
ii) Notepad++
iii) Adobe Dreamweaver
iv) PDT

a) Only iv)
b) i), ii), iii) and iv)
c) i), ii) and iii)
d) Only iii)

Answer: b
Explanation: Any of the above editors can be used to type php code and run it.
5. Which of the following must be installed on your computer so as to run PHP script?

i) Adobe Dreamweaver
ii) XAMPP
iii) Apache and PHP
iv) IIS

a) i), ii), iii) and iv)


b) Only ii)
c) ii) and iii)
d) ii), iii) and iv)

Answer: d
Explanation: To run PHP code you need to have PHP and a web server, both IIS and Apache
are web servers. You can choose either one according to your platform.

6. Which version of PHP introduced Try/catch Exception?


a) PHP 4
b) PHP 5
c) PHP 6
d) PHP 5 and later

Answer: d
Explanation: PHP 5 version and later versions added support for Exception Handling.

7. How should we add a single line comment in our PHP code?

i) /?
ii) //
iii) #
iv) /* */

a) Only ii)
b) i), iii) and iv)
c) ii), iii) and iv)
d) Both ii) and iv)

Answer: c
Explanation: /* */ can also be use to comment just a single line although it is used for
paragraphs. // and # are used only for single line comment.

8. Which of the following PHP statement/statements will store 111 in variable num?

i) int $num = 111;


ii) int mum = 111;
iii) $num = 111;
iv) 111 = $num;

a) Both i) and ii)


b) i), ii), iii) and iv)
c) Only iii)
d) Only i)
Answer: c
Explanation: You need not specify the datatype in php.

9. What will be the output of the following PHP code?

1. <?php
2. $num = 1;
3. $num1 = 2;
4. print $num . "+". $num1;
5. ?>

a) 3
b) 1+2
c) 1.+.2
d) Error

Answer: b
Explanation: .(dot) is used to combine two parts of the statement. Example ($num . “Hello
World”) will output 1Hello World.

10. What will be the output of the following PHP code?

1. <?php
2. $num = "1";
3. $num1 = "2";
4. print $num+$num1;
5. ?>

a) 3
b) 1+2
c) Error
d) 12

Answer: a
Explanation: The numbers inside the double quotes are considered as integers and not string,
therefore the value 3 is printed and not 1+2.

1. Which is the right way of declaring a variable in PHP?

i) $3hello
ii) $_hello
iii) $this
iv) $This

a) Only ii)
b) Only iii)
c) ii), iii) and iv)
d) ii) and iv)

Answer: d
Explanation: A variable in PHP can not start with a number, also $this is mainly used to refer
properties of a class so we can’t use $this as a user define variable name.
advertisement
2. What will be the output of the following PHP code?

1. <?php
2. $foo = 'Bob';
3. $bar = &$foo;
4. $bar = "My name is $bar";
5. echo $bar;
6. echo $foo;
7. ?>

a) Error
b) My name is BobBob
c) My name is BobMy name is Bob
d) My name is Bob Bob

Answer: c
Explanation: Firstly, the line $bar = &$foo; will reference $foo via $bar. So $bar is assigned
value Bob. Therefore $bar = “My name is $bar”; will print My name is Bob($bar=Bob as
said before).

3. Which of the following PHP statements will output Hello World on the screen?

i) echo ("Hello World");


ii) print ("Hello World");
iii) printf ("Hello World");
iv) sprintf ("Hello World");

a) i) and ii)
b) i), ii) and iii)
c) i), ii), iii) and iv)
d) i), ii) and iv)

Answer: b
Explanation: echo(), print() and printf() all three can be used to output a statement onto the
screen. The sprintf() statement is functionally identical to printf() except that the output is
assigned to a string rather than rendered to the browser.

4. What will be the output of the following PHP code?

1. <?php
2. $color = "maroon";
3. $var = $color[2];
4. echo "$var";
5. ?>

a) a
b) Error
c) $var
d) r

Answer: d
Explanation: PHP treats strings in the same fashion as arrays, allowing for specific characters
to be accessed via array offset notation. In an array, index always starts from 0. So in the line
$var = $color[2]; if we count from start ‘r’ comes at index 2. So the output will be r.

5. What will be the output of the following PHP code?

1. <?php
2. $score = 1234;
3. $scoreboard = (array) $score;
4. echo $scoreboard[0];
5. ?>

a) 1
b) Error
c) 1234
d) 2

Answer: c
Explanation: The (array) is a cast operator which is used for converting values from other
data types to array.

6. What will be the output of the following PHP code?

1. <?php
2. $total = "25 students";
3. $more = 10;
4. $total = $total + $more;
5. echo "$total";
6. ?>

a) Error
b) 35 students
c) 35
d) 25 students

Answer: c
Explanation: The integer value at the beginning of the original $total string is used in the
calculation. However if it begins with anything but a numerical value, the value will be 0.

7. Which of the below statements is equivalent to $add += $add?


a) $add = $add
b) $add = $add +$add
c) $add = $add + 1
d) $add = $add + $add + 1

Answer: b
Explanation: a += b is an addition assignment whose outcome is a = a + b. Same can be done
with subtraction, multiplication, division etc.

8. Which statement will output $x on the screen?


a) echo “\$x”;
b) echo “$$x”;
c) echo “/$x”;
d) echo “$x;”;

Answer: a
Explanation: A backslash is used so that the dollar sign is treated as a normal string character
rather than prompt PHP to treat $x as a variable. The backslash used in this manner is known
as escape character.

9. What will be the output of the following PHP code?

1. <?php
2. function track() {
3. static $count = 0;
4. $count++;
5. echo $count;
6. }
7. track();
8. track();
9. track();
10. ?>

a) 123
b) 111
c) 000
d) 011

Answer: a
Explanation: Because $count is static, it retains its previous value each time the function is
executed.

10. What will be the output of the following PHP code?

1. <?php
2. $a = "clue";
3. $a .= "get";
4. echo "$a";
5. ?>

a) get
b) true
c) false
d) clueget

Answer: d
Explanation: ‘.’ is a concatenation operator. $a. = “get” is same as $a=$a.”get” where $a is
having value of “clue” in the previous statement. So the output will be clueget.

1. What will be the output of the following PHP code?

1. <?php
2. $a = 5;
3. $b = 5;
4. echo ($a === $b);
5. ?>

a) 5 === 5
b) Error
c) 1
d) False

Answer: c
Explanation: === operator returns 1 if $a and $b are equivalent and $a and $b have the same
type.
advertisement

2. Which of the below symbols is a newline character?


a) \r
b) \n
c) /n
d) /r

Answer: b
Explanation: PHP treats \n as a newline character.

3. What will be the output of the following PHP code?

1. <?php
2. $num = 10;
3. echo 'What is her age? \n She is $num years old';
4. ?>

a) What is her age? \n She is $num years old


b)

What is her age?


She is $num years old

c) What is her age? She is 10 years old


d)

What is her age?


She is 10 years old
Answer: a
Explanation: When a string is enclosed within single quotes both variables and escape
sequences will not be interpreted when the string is parsed.
 
 

4. Which of the conditional statements is/are supported by PHP?

i) if statements
ii) if-else statements
iii) if-elseif statements
iv) switch statements
a) Only i)
b) i), ii) and iv)
c) ii), iii) and iv)
d) i), ii), iii) and iv)

Answer: d
Explanation: All are conditional statements supported by PHP as all are used to evaluate
different conditions during a program and take decisions based on whether these conditions
evaluate to true of false.

5. What will be the output of the following PHP code?

1. <?php
2. $team = "arsenal";
3. switch ($team) {
4. case "manu":
5. echo "I love man u";
6. case "arsenal":
7. echo "I love arsenal";
8. case "manc":
9. echo "I love manc"; }
10. ?>

a) I love arsenal
b) Error
c) I love arsenalI love manc
d) I love arsenalI love mancI love manu

Answer: c
Explanation: If a break statement isn’t present, all subsequent case blocks will execute until a
break statement is located.

6. Which of the looping statements is/are supported by PHP?

i) for loop
ii) while loop
iii) do-while loop
iv) foreach loop

a) i) and ii)
b) i), ii) and iii)
c) i), ii), iii) and iv)
d) Only iv)

Answer: c
Explanation: All are supported looping statements in PHP as they can repeat the same block
of code a given number of times, or until a certain condition is met.

7. What will be the output of the following PHP code?

1. <?php
2. $user = array("Ashley", "Bale", "Shrek", "Blank");
3. for ($x=0; $x < count($user); $x++) {
4. if ($user[$x] == "Shrek") continue;
5. printf ($user[$x]);
6. }
7. ?>

a) AshleyBale
b) AshleyBaleBlank
c) ShrekBlank
d) Shrek

Answer: b
Explanation: The continue statement causes execution of the current loop iteration to end and
commence at the beginning of the next iteration.

8. If $a = 12 what will be returned when ($a == 12) ? 5 : 1 is executed?


a) 12
b) 1
c) Error
d) 5

Answer: d
Explanation: ?: is known as ternary operator. If condition is true then the part just after the ?
is executed else the part after : .

9. What will be the value of $a and $b after the function call in the following PHP code?

1. <?php
2. function doSomething( &$arg ) {
3. $return = $arg;
4. $arg += 1;
5. return $return;
6. }
7. $a = 3;
8. $b = doSomething( $a );
9. ?>

a) a is 3 and b is 4
b) a is 4 and b is 3
c) Both are 3
d) Both are 4

Answer: b
Explanation: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter
because the return value of the function is a copy of the initial value of the argument.

10. Who is the father of PHP?


a) Rasmus Lerdorf
b) Willam Makepiece
c) Drek Kolkevi
d) List Barely
Answer: a
Explanation: PHP was originally created by Rasmus Lerdorf in 1994

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “In-Built
Functions in PHP”.

1. Which of the following PHP functions accepts any number of parameters?


a) func_get_argv()
b) func_get_args()
c) get_argv()
d) get_argc()

Answer: b
Explanation: func_get_args() returns an array of arguments provided. One can use
func_get_args() inside the function to parse any number of passed parameters. Here is an
example:
1. function foo()
2. {
3. $args = func_get_args();
4. foreach ($args as $k => $v)
5. {
6. echo "arg".($k+1).": $v\n";
7. }
8. }
9. foo();
10. /* will print nothing */
11.  
12. foo("Hello");
13. /* will print Hello */
14.  
15. foo("Hello","World","Bye");
16. /* will print Hello World Bye */

2. Which one of the following PHP functions can be used to find files?
a) glob()
b) file()
c) fold()
d) get_file()

Answer: a
Explanation: The function glob() returns an array of filenames or directories which matches a
specified pattern. The function returns an array of files/directories, or it will return FALSE on
failure. Here is an example-
advertisement
1. // get all php files AND txt files
2. $files = glob('*.{php,txt}', GLOB_BRACE);
3. print_r($files);
4. /* output looks like:
5.   Array
6.   (
7.   [0] => phptest.php
8.   [1] => pi.php
9.   [2] => post_output.php
10.   .
11.   .
12.   .
13.   )

3. Which of the following PHP functions can be used to get the current memory usage?
a) get_usage()
b) get_peak_usage()
c) memory_get_usage()
d) memory_get_peak_usage()

Answer: c
Explanation: memory_get_usage() returns the amount of memory, in bytes, that’s currently
being allocated to the PHP script. We can set the parameter ‘real_usage’ to TRUE to get total
memory allocated from system, including unused pages. If it is not set or FALSE then only
the used memory is reported. To get the highest amount of memory used at any point, we can
use the memory_get_peak_usage() function.

4. Which of the following PHP functions can be used for generating unique ids?
a) uniqueid()
b) id()
c) md5()
d) mdid()

Answer: a
Explanation: The function uniqueid() is used to generate a unique ID based on the microtime
(current time in microseconds). The ID generated from the function uniqueid() is not optimal,
as it is based on the system time. To generate an ID which is extremely difficult to predict we
can use the md5() function.

5. Which one of the following functions can be used to compress a string?


a) zip_compress()
b) zip()
c) compress()
d) gzcompress()

Answer: d
Explanation: The function gzcompress() compresses the string using the ZLIB data format.
One can achieve upto 50% size reduction using this function. The gzuncompress() function is
used to uncompress the string.

6. What will be the output of the following PHP code?

1. <?php
2. echo chr(52);
3. ?>

a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: The chr() function returns a character from the specified ASCII value. We can
specify ASCII value in decimal, octal, or hex values. The Octal values are defined as a
leading 0, while hex values are defined as a leading 0x. Since the ASCII value of 4 is 52, thus
4 was displayed.

7. What will be the output of the following PHP code?

1. <?php
2. echo ord ("hi");
3. ?>

a) 106
b) 103
c) 104
d) 209

Answer: c
Explanation: The ord() function returns the ASCII value of the first character of a string. The
ASCII value of h is 104, thus 104 was displayed.

8. What will be the output of the following PHP code?

1. <?php
2. $str = "Hello World";
3. echo wordwrap($str,5,"<br>\n");
4. ?>

a) Hello World
b)

Hello
World

c)

Hell
o wo
rld

d) World

Answer: b
Explanation: The wordwrap() function wraps a string into new lines when it reaches a
specific length.

9. What will be the output of the following PHP code?

1. <?php
2. echo ucwords("i love my country");
3. ?>
a) I love my country
b) i love my Country
c) I love my Country
d) I Love My Country

Answer: d
Explanation: The ucwords() function converts the first character of each word in a string to
uppercase.

10. What will be the output of the following PHP code?

1. <?php
2. echo lcfirst("welcome to India");
3. ?>

a) welcome to India
b) welcome to india
c) Welcome to India
d) Welcome to india

Answer: a
Explanation: The lcfirst() function converts the first character of a string to lowercase.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Arrays”.

1. PHP’s numerically indexed array begin with position ___________


a) 1
b) 2
c) 0
d) -1

Answer: c
Explanation: Like all the other programming languages, the first element of an array always
starts with ‘0’.

2. Which of the following are correct ways of creating an array?

i) state[0] = "karnataka";
ii) $state[] = array("karnataka");
iii) $state[0] = "karnataka";
iv) $state = array("karnataka");

a) iii) and iv)


b) ii) and iii)
c) Only i)
d) ii), iii) and iv)

Answer: a
Explanation: A variable name should start with $ symbol which is not present in i) and you
need not put the square brackets when you use the array() constructor.
advertisement
3. What will be the output of the following PHP code?

1. <?php
2. $states = array("Karnataka" => array
3. ("population" => "11,35,000", "capital" => "Bangalore"),
4. "Tamil Nadu" => array( "population" => "17,90,000",
5. "capital" => "Chennai") );
6. echo $states["Karnataka"]["population"];
7. ?>

a) Karnataka 11,35,000
b) 11,35,000
c) population 11,35,000
d) Karnataka population

Answer: b
Explanation: In the following PHP code, the variable states are treated as a multidimensional
array and accordingly traverse it to get the value of ‘Karnataka’s population’.

4. Which of the following PHP function will return true if a variable is an array or false if it is
not an array?
a) this_array()
b) is_array()
c) do_array()
d) in_array()

Answer: b
Explanation: The function is_array() is an inbuilt function in PHP which is used to check
whether a variable is an array or not. Its prototype follows: boolean is_array(mixed variable).

5. Which in-built function will add a value to the end of an array?


a) array_unshift()
b) into_array()
c) inend_array()
d) array_push()

Answer: d
Explanation: array_push adds a value to the end of an array, returning the total count of
elements in the array after the new value has been added.

6. What will be the output of the following PHP code?

1. <?php
2. $state = array ("Karnataka", "Goa", "Tamil Nadu",
3. "Andhra Pradesh");
4. echo (array_search ("Tamil Nadu", $state) );
5. ?>

a) True
b) 1
c) False
d) 2
Answer: d
Explanation: The array_search() function searches an array for a specified value, returning its
key if located and FALSE otherwise.

7. What will be the output of the following PHP code?

1. <?php
2. $fruits = array ("apple", "orange", "banana");
3. echo (next($fruits));
4. echo (next($fruits));
5. ?>

a) orangebanana
b) appleorange
c) orangeorange
d) appleapple

Answer: a
Explanation: The next() function returns the value of the next element in the array. In the first
‘next($fruits)’ call, it will print orange which is next to apple and so on.

8. Which of the following function is used to get the value of the previous element in an
array?
a) last()
b) before()
c) prev()
d) previous()

Answer: c
Explanation: The prev() function returns the previous element in the array.

9. What will be the output of the following PHP code?

1. <?php
2. $fruits = array ("apple", "orange", array ("pear", "mango"),
3. "banana");
4. echo (count($fruits, 1));
5. ?>

a) 3
b) 4
c) 5
d) 6

Answer: d
Explanation: The function count() will return the number of elements in an array. The
parameter 1 counts the array recursively i.e it will count all the elements of multidimensional
arrays.

10. Which function returns an array consisting of associative key/value pairs?


a) count()
b) array_count()
c) array_count_values()
d) count_values()

Answer: c
Explanation: The function array_count_values() will count all the values of an array. It will
return an associative array, where the keys will be the original array’s values, and the values
are the number of occurrences.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “File System and
PHP”.

1. The filesize() function returns the file size in ___________


a) bits
b) bytes
c) kilobytes
d) gigabytes

Answer: b
Explanation: The function filesize() returns the size of the specified file and it returns the file
size in bytes on success or FALSE on failure.

2. Which one of the following PHP function is used to determine a file’s last access time?
a) fileltime()
b) filectime()
c) fileatime()
d) filetime()

Answer: c
Explanation: The fileatime() function returns a file’s last access time in Unix timestamp
format or FALSE on error.

3. Which one of the following function is capable of reading a file into an array?
a) file()
b) arrfile()
c) arr_file()
d) file_arr()

Answer: a
Explanation: The function file() will read the entire file into an array.
advertisement

4. Which one of the following function is capable of reading a file into a string variable?
a) file_contents()
b) file_get_contents()
c) file_content()
d) file_get_content()

Answer: b
Explanation: The function file_get_contents() reads a file into a string. This is the preferred
way to read the contents of a file into a string as it will use memory mapping techniques.
5. Which one of the following function is capable of reading a specific number of characters
from a file?
a) fgets()
b) fget()
c) fileget()
d) filegets()

Answer: a
Explanation: The function fgets() will return a line from an open file. This stops returning on
a new line, at the specified length, or at EOF, whichever comes first. Its prototype is string
fgets(resource handle [, int length]). If the optional length parameter is omitted, 1024
character is assumed.

6. Which one of the following function operates similarly to fgets(), except that it also strips
any HTML and PHP tags form the input?
a) fgetsh()
b) fgetsp()
c) fgetsa()
d) fgetss()

Answer: d
Explanation: The function fgetss() returns a line, with HTML and PHP tags removed, from an
open file. This function operates similarly to fgets(), except that it also strips any HTML and
PHP tags form the input.

7. Which one of the following function outputs the contents of a string variable to the
specified resource?
a) filewrite()
b) fwrite()
c) filewrites()
d) fwrites()

Answer: b
Explanation: The function fwrite() writes to an open file. This will stop at the end of the file
or when it reaches the specified length, whichever comes first.

8. Which function sets the file filename last-modified and last-accessed times?
a) sets()
b) set()
c) touch()
d) touched()

Answer: c
Explanation: The function touch() will set the access and modification time of the specified
file. Syntax is touch(filename, time, atime).

9. Which function is useful when you want to output the executed command result?
a) out_cmm()
b) out_system()
c) cmm()
d) system()

Answer: d
Explanation: The function system() in PHP is same as the C version of the function as in that
it executes the given command and outputs the result. This function also tries to
automatically flush the web server’s output buffer after each line of output if PHP is running
as a server module.

10. Which one of the following function reads a directory into an Array?
a) scandir()
b) readdir()
c) scandirectory()
d) readdirectory()

Answer: a
Explanation: It returns an array consisting of files and directories found in directory or returns
FALSE on error

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Uploading Files
with PHP”.

1. Which directive determines whether PHP scripts on the server can accept file uploads?
a) file_uploads
b) file_upload
c) file_input
d) file_intake

Answer: a
Explanation: With PHP, it is easy to upload files to the server. We need to ensure that PHP is
configured to allow file uploads. In the “php.ini” file, search for the file_uploads directive,
and set it to On. By default, its value is on.

2. Which of the following directive determines the maximum amount of time that a PHP
script will spend attempting to parse input before registering a fatal error?
a) max_take_time
b) max_intake_time
c) max_input_time
d) max_parse_time

Answer: c
Explanation: This is relevant because particularly large files can take some time to upload,
eclipsing the time set by this directive.

3. What is the default value of max_input_time directive?


a) 30 seconds
b) 60 seconds
c) 120 seconds
d) 1 second
Answer: b
Explanation: The default value of the max_input_time directive is 60 seconds.
advertisement

4. Since which version of PHP was the directive max_file_limit available.


a) PHP 5.2.1
b) PHP 5.2.2
c) PHP 5.2.12
d) PHP 5.2.21

Answer: c
Explanation: The max_file_limit directive sets an upper limit on the number of files which
can be simultaneously uploaded.

5. What is the default value of the directive max_file_limit?


a) 10 files
b) 15 files
c) 20 files
d) 25 files

Answer: c
Explanation: The default value of the directive max_file_limit is 20 files.

6. Which directive sets a maximum allowable amount of memory in megabytes that a script
can allow?
a) max_size
b) post_max_size
c) max_memory_limit
d) memory_limit

Answer: d
Explanation: Its default value is 16M.

7. If you want to temporarily store uploaded files in the /tmp/phpuploads/ directory, which
one of the following statement will you use?
a) upload_tmp_dir “/tmp/phpuploads/ directory”
b) upload_dir “/tmp/phpuploads/ directory”
c) upload_temp_dir “/tmp/phpuploads/ directory”
d) upload_temp_director “/tmp/phpuploads/ directory”

Answer: a
Explanation: Anyone can temporarily store uploaded files on the given directory. One cannot
change upload_tmp_dir at the runtime. By the time a script runs, the upload process has
already occurred.

8. Which superglobal stores a variety of information pertinent to a file uploaded to the server
via a PHP script?
a) $_FILE Array
b) $_FILES Array
c) $_FILES_UPLOADED Array
d) $_FILE_UPLOADED Array

Answer: b
Explanation: The superglobal $_FILES is a two-dimensional associative global array of items
which are being uploaded by via HTTP POST method and holds the attributes of files.

9. How many items are available in the $_FILES array?


a) 2
b) 3
c) 4
d) 5

Answer: d
Explanation: $_FILEs[‘userfile’][‘error’], $_FILEs[‘userfile’][‘name’], $_FILEs[‘userfile’]
[‘size’], $_FILEs[‘userfile’][‘tmp_name’], $_FILEs[‘userfile’][‘type’] are the five items in
the array.

10. Which function is used to determine whether a file was uploaded?


a) is_file_uploaded()
b) is_uploaded_file()
c) file_uploaded(“filename”)
d) uploaded_file(“filename”)

Answer: b
Explanation: The function is_uploaded_file() checks whether the specified file is uploaded
via HTTP POST. The syntax is is_uploaded_file(file).

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Date and
Timestamp”.

1. What will be the output of the following PHP code?

1. <?php
2. echo (checkdate(4,31,2010) ? 'Valid' : 'Invalid');
3. ?>

a) TRUE
b) FALSE
c) Valid
d) Invalid

Answer: d
Explanation: The function checkdate() is used to validate a Gregorian date. In the program,
April has 30 days and the above date is 31 therefore Invalid is returned.
advertisement

2. The date() function returns ___ representation of the current date and/or time.
a) Integer
b) String
c) Boolean
d) Float

Answer: b
Explanation: The function date() is used to format a local date and time, and it will return the
formatted date string. The syntax of this function is string date(string format [, int
timestamp]).

3. Which one of the following format parameter can be used to identify timezone?
a) T
b) N
c) E
d) I

Answer: c
Explanation: When the format is E the time zone is identified and returned, for example,
America/New York. N denotes ISO-8601 numeric representation of the day of the week, T
denotes time zone abbreviation, I denotes whether or not the date is in daylight saving time.

4. If the format is F then which one of the following will be returned?


a) Complete text representation of month
b) Day of month, with leading zero
c) Daylight saving time
d) Day of month, without zeros

Answer: a
Explanation: F represents a full textual representation of a month, such as January or March.
Day of month, with leading zero is represented by D, Daylight saving time by I, Day of
month without zeros by j.

5. What will be the output of the following code? (If say date is 22/06/2013.)

1. <?php
2. echo "Today is ".date("F d, Y");
3. ?>

a) Today is 22 June, 2013


b) Today is 22-06-2013
c) Today is 06-22-2013
d) Today is June 22, 2013

Answer: d
Explanation: The function date() is used to format a local date and time, and it will return the
formatted date string. F is the parameter for complete text representation of month, d for day
of month, and Y for 4 digit representation of year.

6. Which one of the following function is useful for producing a timestamp based on a given
date and time?
a) time()
b) mktime()
c) mrtime()
d) mtime()

Answer: b
Explanation: The function mktime() returns the Unix timestamp for a date. This function is
same as gmmktime() except that the passed parameters represents a date not a GMT date.

7. Which function displays the web page’s most recent modification date?
a) lastmod()
b) getlastmod()
c) last_mod()
d) get_last_mod()

Answer: b
Explanation: The function getlastmod() gets the time of the last modification of the main
script of execution. It returns the value of the page’s last modified header or FALSE in the
case of an error.

8. What will be the output of the following PHP code? (If say date is 22/06/2013.)

1. <?php
2. printf( date("t") );
3. ?>

a) 30
b) 22
c) JUNE
d) 2013

Answer: a
Explanation: The t parameter is used to determine the number of days in the current month.

9. Suppose you want to calculate the date 45 days from the present date which one of the
following statement will you use?
a) totime(“+45”)
b) totime(“+45 days”)
c) strtotime(“+45 days”)
d) strtotime(“-45 days”)

Answer: c
Explanation: The strtotime() function and GNU date syntax is used to calculating the date x
days from the present date.

10. To create an object and set the date to JUNE 22, 2013, which one of the following
statement should be executed?
a) $date = Date(“22 JUNE 2013”)
b) $date = new Date(“JUNE 22 2013”)
c) $date = DateTime(“22 JUNE 2013”)
d) $date = new DateTime(“22 JUNE 2013”)
Answer: d
Explanation: The dateTime() method is class constructor. You can set the date either at the
time of instantiation or later by using a variety of mutators.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Working with
Dates”.

1. How many methods does the DateTime class have?


a) 8
b) 9
c) 10
d) 11

Answer: b
Explanation: The DateTime class has nine methods, all of which are public.

2. How many constants does the DateTime class have?


a) 8
b) 9
c) 10
d) 11

Answer: d
Explanation: The DateTime class has 11 constants, no static properties or methods.

3. Which method is simply an object-oriented version of date()?


a) DateTime::format()
b) DateTime::modify()
c) DateTime::setTime()
d) DateTime::setDate()

Answer: a
Explanation: The format() method is simply an object-oriented version of date(). It takes
$dateFormat as an argument. $dateFormat is a string consisting of the same date formatting
characters accepted by the procedural date() function.
advertisement

4. Which of the following is the right way to use the DateTime class?
a) $date = get_Class(DateTime);
b) $date = class DateTime;
c) $date = new DateTime();
d) $date = new class DateTime();

Answer: c
Explanation: The way you use the DateTime class is like any other class: instantiate an
object, and store it in a variable.

5. What will be the output of the following PHP code if date is 24/02/2008?

1. <?php
2. $date = new DateTime();
3. echo $date->format('l,F,js,Y');
4. ?>

a) Sunday, February 24th 2008


b) Sunday, 02 24 2008
c) Sunday, 24 02 2008
d) Sunday, 24th February 2008

Answer: a
Explanation: The format() method displays the date in same way as standard date function().

6. Which of the following statements can be used to set the time zone in individual scripts?
a) date_set_timezone(‘Europe/London’);
b) date_default_timezone_set(‘Europe/London’);
c) date_set_default_timezone(‘Europe/London’);
d) date_default_timezone(‘Europe/London’);

Answer: b
Explanation: The function date_default_timezone_set is used to set the default time zone used
by all date/time functions in a script. You can also use ini_set(‘date.timezone’,
‘Europe/London’);

7. Which of the following DateTimeZone classes are static?

i) listAbbreviations()
ii) getName()
iii) getOffset()
iv) listIdentifiers()

a) Only i)
b) Only ii)
c) i) and iv)
d) iii) and iv)

Answer: c
Explanation: listAbbreviations() and listIdentifiers() are static methods.

8. Which of the following DateTimeZone classes are non-static?

i) _construct()
ii) getName()
iii) getOffset()
iv) getTransitions()

a) Only i)
b) Only ii)
c) i), ii), iii) and iv)
d) iii) and iv)

Answer: c
Explanation: All of the given methods are non static.
9. Which of the following statements can be used to add two months to the existing date?
a) $date->modify(‘+2 months’);
b) $date = modify(‘+2 months’);
c) $date = modify(‘2+ months’);
d) $date->modify(‘2+ months’);

Answer: a
Explanation: To change the date stored by a DateTime object after it has been created, you
use DateTime::modify() with a natural language expression.

10. Which method enables you to calculate whether daylight saving time is in force at a
specific date and time?
a) getOffset()
b) getTranitions()
c) ISODate()
d) savingTime()

Answer: b
Explanation: This outputs a multidimensional array listing past and future changes to the
offset from UTC for a DateTimeZone object.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Session
Handling-1”.

1. Which one of the following is the very first task executed by a session enabled page?
a) Delete the previous session
b) Start a new session
c) Check whether a valid session exists
d) Handle the session

Answer: c
Explanation: The session variables are set with the PHP global variable which is
$_SESSION. The very first task executed by a session enabled page is Check whether a valid
session exists.

2. How many ways can a session data be stored?


a) 3
b) 4
c) 5
d) 6

Answer: b
Explanation: Within flat files(files), within volatile memory(mm), using the SQLite
database(sqlite), or through user defined functions(user).

3. Which directive determines how the session information will be stored?


a) save_data
b) session.save
c) session.save_data
d) session.save_handler
Answer: d
Explanation: The class SessionHandler is used to wrap whatever internal save handler is set
as defined by the session.save_handler configuration directive which is usually files by
default.
advertisement

4. Which one of the following is the default PHP session name?


a) PHPSESSID
b) PHPSESID
c) PHPSESSIONID
d) PHPIDSESS

Answer: a
Explanation: You can change this name by using the session.name directive.

5. If session.use_cookie is set to 0, this results in use of _____________


a) Session
b) Cookie
c) URL rewriting
d) Nothing happens

Answer: c
Explanation: The URL rewriting allows to completely separate the URL from the resource.
URL rewriting can turn unsightly URLs into nice ones with a lot less agony and expense than
picking a good domain name. It enables to fill out your URLs with friendly, readable
keywords without affecting the underlying structure of pages.

6. If the directive session.cookie_lifetime is set to 3600, the cookie will live until
____________
a) 3600 sec
b) 3600 min
c) 3600 hrs
d) the browser is restarted

Answer: a
Explanation: The lifetime is specified in seconds, so if the cookie should live 1 hour, this
directive should be set to 3600.

7. Neglecting to set which of the following cookie will result in the cookie’s domain being set
to the host name of the server which generated it.
a) session.domain
b) session.path
c) session.cookie_path
d) session.cookie_domain

Answer: d
Explanation: The directive session.cookie_domain determines the domain for which the
cookie is valid.
8. What is the default number of seconds that cached session pages are made available before
the new pages are created?
a) 360
b) 180
c) 3600
d) 1800

Answer: b
Explanation: The directive which determines this is session.cache_expire.

9. What is the default time(in seconds) for which session data is considered valid?
a) 1800
b) 3600
c) 1440
d) 1540

Answer: c
Explanation: The session.gc_maxlifetime directive determines this duration. It can be set to
any required value.

10. Which one of the following function is used to start a session?


a) start_session()
b) session_start()
c) session_begin()
d) begin_session()

Answer: b
Explanation: A session is started with the function session_start() . The session variables are
set with the PHP global variable which is $_SESSION.

This set of PHP test focuses on “Session Handling-2”.

1. Which function is used to erase all session variables stored in the current session?
a) session_destroy()
b) session_change()
c) session_remove()
d) session_unset()

Answer: d
Explanation: The function session_unset() frees all session variables that is currently
registered. This will not completely remove the session from the storage mechanism. If you
want to completely destroy the session, you need to use the function session_destroy().

2. What will the function session_id() return is no parameter is passed?


a) Current Session Identification Number
b) Previous Session Identification Number
c) Last Session Identification Number
d) Error
Answer: a
Explanation: The function session_id() will return the session id for the current session or the
empty string (” “) if there is no current session.

3. Which one of the following statements should you use to set the session username to
Nachi?
a) $SESSION[‘username’] = “Nachi”;
b) $_SESSION[‘username’] = “Nachi”;
c) session_start(“nachi”);
d) $SESSION_START[“username”] = “Nachi”;

Answer: b
Explanation: You need to refer the session variable ‘username’ in the context of the
$_SESSION superglobal.
advertisement

4. What will be the output of the following PHP code? (Say your previous session username
was nachi.)

1. unset($_SESSION['username']);
2. printf("Username now set to: %s", $_SESSION['username']);

a) Username now set to: nachi


b) Username now set to: System
c) Username now set to:
d) Error

Answer: c
Explanation: If someone want to destroy a single session variable then they can use the
function unset () to unset a session variable. To delete the session variable ‘username’ we use
the unset () function.

5. An attacker somehow obtains an unsuspecting user’s SID and then using it to impersonate
the user in order to gain potentially sensitive information. This attack is known as
__________
a) session-fixation
b) session-fixing
c) session-hijack
d) session-copy

Answer: a
Explanation: The attack session fixation attempts to exploit the vulnerability of a system that
allows one person to set another person’s session identifier. You can minimize this risk by
regenerating the session ID on each request while maintaining the session-specific data. PHP
offers a convenient function named session_regenerate_id() that will replace the existing ID
with a new one.

6. Which parameter determines whether the old session file will also be deleted when the
session ID is regenerated?
a) delete_old_file
b) delete_old_session
c) delete_old_session_file
d) delete_session_file

Answer: b
Explanation: The parameter delete_old_session determines whether the old session file will
also be deleted when the session ID is regenerated.

7. Which function effectively deletes all sessions that have expired?


a) session_delete()
b) session_destroy()
c) session_garbage_collect()
d) SessionHandler::gc

Answer: d
Explanation: SessionHandler::gc is used to clean up expired sessions. It is called randomly by
PHP internally when a session_start() is invoked.

8. Which function is used to transform PHP’s session-handler behavior into that defined by
your custom handler?
a) session_set_save()
b) session_set_save_handler()
c) Session_handler()
d) session_save_handler()

Answer: b
Explanation: The function session_set_save_handler() is used to set the user-level session
storage functions which are used for storing and retrieving data associated with a session.

9. The session_start() function must appear _________


a) after the html tag
b) after the body tag
c) before the body tag
d) before the html tag

Answer: d
Explanation: Like this: <?php session_start(); ?> <html>

10. What is the return type of session_set_save_handler() function?


a) boolean
b) integer
c) float
d) character

Answer: a
Explanation: Returns TRUE on success or FALSE on failure.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “HTML Forms”.
1. Which two predefined variables are used to retrieve information from forms?
a) $GET & $SET
b) $_GET & $_SET
c) $__GET & $__SET
d) GET & SET

Answer: b
Explanation: The global variables $_GET is used to collect form data after submitting an
HTML form with the method=”get”. The variable $_SET is also used to retrieve information
from forms.

2. The attack which involves the insertion of malicious code into a page frequented by other
users is known as _______________
a) basic sql injection
b) advanced sql injection
c) cross-site scripting
d) scripting

Answer: c
Explanation: The cross-site scripting attack is among one of the top five security attacks
carried out across the Internet. It is also known as XSS, this attack is a type of code injection
attack which is made possible by incorrectly validating user data, which usually gets inserted
into the page through a web form or using an altered hyperlink.

3. When you use the $_GET variable to collect data, the data is visible to ___________
a) none
b) only you
c) everyone
d) selected few

Answer: c
Explanation: The information sent from a form with the method GET is visible to everyone
i.e. all variable names and values are displayed in the URL.
advertisement

4. When you use the $_POST variable to collect data, the data is visible to ___________
a) none
b) only you
c) everyone
d) selected few

Answer: b
Explanation: The information sent from a form with the method POST is invisible to others
i.e. all names/values are embedded within the body of the HTTP request.

5. Which variable is used to collect form data sent with both the GET and POST methods?
a) $BOTH
b) $_BOTH
c) $REQUEST
d) $_REQUEST
Answer: d
Explanation: In PHP the global variable $_REQUEST is used to collect data after submitting
an HTML form.

6. Which one of the following should not be used while sending passwords or other sensitive
information?
a) GET
b) POST
c) REQUEST
d) NEXT

Answer: a
Explanation: The information sent from a form with the method GET is visible to everyone
i.e. all variable names and values are displayed in the URL. So, it should not be used while
sending passwords or other sensitive information.

7. Which function is used to remove all HTML tags from a string passed to a form?
a) remove_tags()
b) strip_tags()
c) tags_strip()
d) tags_remove()

Answer: b
Explanation: The function strip_tags() is used to strip a string from HTML, XML, and PHP
tags.

8. What will be the value of the variable $input in the following PHP code?

1. <?php
2. $input = "Swapna<td>Lawrence</td>you are really<i>pretty</i>!";
3. $input = strip_tags($input,"<i></i>");
4. echo $input;
5. ?>

a) Swapna Lawrence you are really pretty!


b) Swapna <td>Lawrence</td> you are really<i>pretty</i>!
c) Swapna <td>Lawrence</td> you are really pretty!
d) Swapna Lawrence you are really<i>pretty</i>!

Answer: d
Explanation: Italic tags <i></i> might be allowable, but table tags <td></td> could
potentially wreak havoc on a page.

9. To validate an email address, which flag is to be passed to the function filter_var()?


a) FILTER_VALIDATE_EMAIL
b) FILTER_VALIDATE_MAIL
c) VALIDATE_EMAIL
d) VALIDATE_MAIL

Answer: a
Explanation: The FILTER_VALIDATE_EMAIL is used to validates an e-mail address.
10. How many validation filters like FILTER_VALIDATE_EMAIL are currently available?
a) 5
b) 6
c) 7
d) 8

Answer: c
Explanation: There are seven validation filters. They are FILTER_VALIDATE_EMAIL,
FILTER_VALIDATE_BOOLEAN, FILTER_VALIDATE_FLOAT,
FILTER_VALIDATE_INT, FILTER_VALIDATE_IP, FILTER_VALIDATE_REGEXP,
FILTER_VALIDATE_URL.

This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “User
Authentication”.

1. How many predefined variables does PHP use to authenticate a user?


a) 1
b) 2
c) 3
d) 4

Answer: b
Explanation: The variables PHP use to authenticate a user are
$_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’].

2. Which of the following variables does PHP use to authenticate a user?

i) $_SERVER['PHP_AUTH_USER'].
ii) $_SERVER['PHP_AUTH_USERS'].
iii) $_SERVER['PHP_AUTH_PU'].
iv) $_SERVER['PHP_AUTH_PW'].

a) i) and ii)
b) ii) and iv)
c) i) and iv)
d) ii) and iii)

Answer: c
Explanation: $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’] store
the username and password values, respectively.
advertisement

3. Which of the following PHP function is commonly used when handling authentication via
PHP?

i) header()
ii) footer()
iii) inset()
iv) isset()
a) i) and iv)
b) ii) and iv)
c) ii) and iii)
d) i) and iii)

Answer: a
Explanation: The function isset () is used to check whether a variable is set or not and the
function header() sends a raw HTTP header to a client.

4. Which function is used to verify whether a variable contains a value?


a) header()
b) footer()
c) inset()
d) isset()

Answer: d
Explanation: The isset() function determines whether a variable has been assigned a value. Its
prototype follows: boolean isset(mixed var [,mixed var [,…]]).

5. Which of the following are types of PHP authentication implementation methodologies?

i) Hard-coding a login pair directly into the script


ii) File-based authentication
iii) Data-based authentication
iv) PEAR'S HTTP authentication

a) ii) and iii)


b) i) and iv)
c) i), ii), iii) and iv)
d) Only iv)

Answer: c
Explanation: The method PEAR’S HTTP authentication is used to provides a framework for
user authentication on the HTTP. The data-based authentication is the process of confirming
that a user who is attempting to log in to a database is authorized to do so. In the file-based
authentication as some small sites does not have a need for database back-end to store data,
but security is still important either the site is big or small. They need to authenticate some
folder or file and want to set access credentials for that. One can handle such by using file-
based authentication using PHP. The simplest way to restrict resource access is by hard-
coding the username and password directly into the script.

6. In which authentication method does changing the username or password can be done only
by entering the code and making the manual adjustment.
a) Hard-coding a login pair directly into the script
b) File-based authentication
c) Data-based authentication
d) PEAR’S HTTP authentication

Answer: a
Explanation: The simplest way to restrict resource access is by hard-coding the username and
password directly into the script. In this authentication method, changing the username or
password can be done only by entering the code and making the manual adjustment. This is
one of the drawbacks of hard-coding a login pair directly into the script.

7. The authenticationFile.txt, the file which stores username and password should be stored
___ the server document root.
a) Inside
b) Outside
c) Within
d) None of the mentioned

Answer: b
Explanation: If it is not stored outside, the attacker could discover the file through brute force
guessing.

8. Which function is used to split a string into a series of substrings, with each string
boundary is determined by a specific separator?
a) break()
b) divide()
c) explode()
d) md5()

Answer: c
Explanation: Although they are a similar function, you should use explode() instead of split().
In fact split() function has been deprecated altogether.

9. In which of the following situations does file-based authentication become inconvenient.

i) small list
ii) large number of user
iii) users are being regularly added
iv) static authentication

a) i) and iv)
b) i) and iii)
c) ii) and iii)
d) ii) and iv)

Answer: c
Explanation: Such requirements are better satisfied by implementing a database based
solution.

10. Which is the most powerful authentication method among the four?
a) Hard-coding a login pair directly into the script
b) File-based authentication
c) Data-based authentication
d) PEAR’S HTTP authentication

Answer: c
Explanation: It not only enhances administrative convenience and scalability but also can be
integrated into a larger database infrastructure.
This set of PHP Multiple Choice Questions & Answers (MCQs) focuses on “Functions”.

1. How to define a function in PHP?


a) function {function body}
b) data type functionName(parameters) {function body}
c) functionName(parameters) {function body}
d) function functionName(parameters) {function body}

Answer: d
Explanation: PHP allows us to create our own user-defined functions. Any name ending with
an open and closed parenthesis is a function. The keyword function is always used to begin a
function.

2. Type Hinting was introduced in which version of PHP?


a) PHP 4
b) PHP 5
c) PHP 5.3
d) PHP 6

Answer: b
Explanation: PHP 5 introduced the feature of type hinting. With the help of type hinting, we
can specify the expected data type of an argument in a function declaration. First valid types
can be the class names for arguments that receive objects and the other are array for those
that receive arrays.

3. Which type of function call is used in line 8 in the following PHP code?

advertisement
1. <?php
2. function calc($price, $tax)
3. {
4. $total = $price + $tax;
5. }
6. $pricetag = 15;
7. $taxtag = 3;
8. calc($pricetag, $taxtag);
9. ?>

a) Call By Value
b) Call By Reference
c) Default Argument Value
d) Type Hinting

Answer: a
Explanation: If we call a function by value, we actually pass the values of the arguments
which are stored or copied into the formal parameters of the function. Hence, the original
values are unchanged only the parameters inside the function changes.

4. What will be the output of the following PHP code?

1. <?php
2. function calc($price, $tax="")
3. {
4. $total = $price + ($price * $tax);
5. echo "$total";
6. }
7. calc(42);
8. ?>

a) Error
b) 0
c) 42
d) 84

Answer: c
Explanation: You can designate certain arguments as optional by placing them at the end of
the list and assigning them a default value of nothing.

5. Which of the following are valid function names?

i) function()
ii) €()
iii) .function()
iv) $function()

a) Only i)
b) Only ii)
c) i) and ii)
d) iii) and iv)

Answer: b
Explanation: A valid function name can start with a letter or underscore, followed by any
number of letters, numbers, or underscores. According to the specified regular expression ([a-
zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*), a function name like this one is valid.

6. What will be the output of the following PHP code?

1. <?php
2. function a()
3. {
4. function b()
5. {
6. echo 'I am b';
7. }
8. echo 'I am a';
9. }
10. a();
11. a();
12. ?>

a) I am a
b) I am bI am a
c) Error
d) I am a Error
Answer: a
Explanation: The output will be “I am a” as we are calling a(); so the statement outside the
block of function b() will be called.

7. What will be the output of the following PHP code?

1. <?php
2. function a()
3. {
4. function b()
5. {
6. echo 'I am b';
7. }
8. echo 'I am a';
9. }
10. b();
11. a();
12. ?>

a) I am b
b) I am bI am a
c) Error
d) I am a Error

Answer: c
Explanation: The output will be Fatal error: Call to undefined function b(). You cannot call a
function which is inside a function without calling the outside function first. It should be a();
then b();

8. What will be the output of the following PHP code?

1. <?php
2. $op2 = "blabla";
3. function foo($op1)
4. {
5. echo $op1;
6. echo $op2;
7. }
8. foo("hello");
9. ?>

a) helloblabla
b) Error
c) hello
d) helloblablablabla

Answer: c
Explanation: If u want to put some variables in function that was not passed by it, you must
use “global”. Inside the function type global $op2.

9. A function in PHP which starts with __ (double underscore) is known as __________


a) Magic Function
b) Inbuilt Function
c) Default Function
d) User Defined Function

Answer: a
Explanation: PHP functions that start with a double underscore – a “__” – are called magic
functions in PHP. They are functions that are always defined inside classes, and are not
stand-alone functions.

10. What will be the output of the following PHP code?

1. <?php
2. function foo($msg)
3. {
4. echo "$msg";
5. }
6. $var1 = "foo";
7. $var1("will this work");
8. ?>

a) Error
b) $msg
c) 0
d) Will this work

Answer: d
Explanation: It is possible to call a function using a variable which stores the function name.

1. How many ways user can print output in PHP?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : B

Explanation: there are two basic ways to get output in PHP:-echo, print.

2. print statement can take _____ argument?

A. 1
B. 2
C. 3
D. 4

View Answer
Ans : A

Explanation: print can take one argument.

3. How many return value does echo statement has?

A. 1
B. 2
C. 3
D. 0

View Answer

Ans : D

Explanation: echo has no return value

4. Echo statement is written under parentheses?

A. True
B. False
C. Only for string it written under parentheses
D. Only for variable it written under parentheses

View Answer

Ans : B

Explanation: Echo statement does not written under parentheses.

5. Which statement is faster amoung echo and print?

A. echo
B. print
C. echo and print has same speed
D. None of the above

View Answer

Ans : A

Explanation: Echo is faster than print.


6. What will be the output of the following PHP code?

<?php
echo "Hello world </br> I am learning PHP at letsfindcourse";
?>

A. Hello world
B. Hello world I am learning PHP at letsfindcourse
C. Hello world
I am learning PHP at letsfindcourse
D. Error

View Answer

Ans : C

Explanation: The break tag is used as break line.

7. What will be the output of the following PHP code?

<?php
$five = 5;
print($five);
print $five;
?>

A. 05
B. 55
C. 50
D. Error

View Answer

Ans : B

Explanation: Print can be used with or without parentheses.

8. What will be the output of the following PHP code?

<?php
$a = "Hello";
$b = "World";
echo "$a"+"$b";
?>

A. HelloWorld
B. Hello+World
C. 0
D. Error

View Answer

Ans : C

Explanation: In an echo statement, you can not use plus sign to join two strings.

9. What will be the output of the following PHP code?

<?php
$a = "hello";
$b = "world";
print($a$b);
?>

A. helloworld
B. hello
C. Nothing
D. error

View Answer

Ans : D

Explanation: The above syntax will produce an error, unlike the echo statement.

1. Any variables declared in PHP must begin with a _____?

A. .
B. #
C. &
D. $

View Answer

Ans : D

Explanation: Any variables declared in PHP must begin with a dollar sign ($)

2. A variable can have ________?

A. long descriptive names


B. short names
C. Both A and B
D. None of the above
View Answer

Ans : C

Explanation: A variable can have long descriptive names (like $factorial, $even_nos) or short
names (like $n or $f or $x)

3. A variable name can only contain ____________?

A. alphanumeric characters
B. underscores
C. Both A and B
D. None of the above

View Answer

Ans : C

Explanation: A variable name can only contain alphanumeric characters and underscores in
their name.

4. Variable names in PHP must start with ?

A. letter
B. underscore
C. no numbers
D. All of the above

View Answer

Ans : D

Explanation: One must keep in mind that variable names in PHP must start with a letter or
underscore and should not start with numbers.

5. PHP variables are case-sensitive?

A. True
B. False
C. For "sum" variable it is case-sensitive
D. None of the above

View Answer
Ans : A

Explanation: PHP variables are case-sensitive, i.e., $lfc and $LFC are treated differently.

6. How many variable scope are there in php?

A. 2
B. 3
C. 1
D. 4

View Answer

Ans : B

Explanation: Depending on the scopes, PHP has three variable scopes: Local, Global and
static variable scope.

7. What will be the output of the following PHP code?

<?php
$x = 1;
$y = 2;
$z = "$x + $y";
echo "$z";
?<

A. $x + $y
B. 3
C. 1+2
D. 12

View Answer

Ans : C

Explanation: Variable z will store 1 + 2 because 1 + 2 is given in double-quotes.

8. What will be the output of the following PHP code?

<?php
$x = 3.3;
$y = 2;
echo $x % $y;
?>
A. 1.3
B. 1
C. 0
D. Error

View Answer

Ans : B

Explanation: % is the modulo operator. Unlike in C, we can use it to get a reminder or


floating-point numbers in PHP.

9. What will be the output of the following PHP code?

<?php
$a = 1;
$b = 2;
$c = 3;
echo ($a % ($b) + $c);
?>

A. 2
B. 3
C. 4
D. 5

View Answer

Ans : A

Explanation: The innermost bracket is evaluated first, since it covers only variable b it is as
good as not using brackets.

10. What will be the output of the following PHP code?

<?php
$a = 1;
$b = 2;
$c = 3;
echo ($a * (($b) - $c));
?>

A. 1
B. -1
C. 2
D. -2

View Answer
Ans : B

Explanation: The innermost bracket is evaluated first since it covers only variable B, it is as
good as not using brackets, then $b- $c action will be performed.

1. How many different data types are available in php?

A. 6
B. 7
C. 8
D. 9

View Answer

Ans : C

Explanation: PHP allows eight different data types.

2. How many compound data types are available in php?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : C

Explanation: The first five are called simple data types and the last three are compound data
types.

3. Which one is not a data type in PHP?

A. Resources
B. Objects
C. Null
D. Void

View Answer

Ans : D

Explanation: The void is not a data type in PHP.


4. The range of integers must lie between ___________?

A. -2^15 to 2^15.
B. -2^16 to 2^16.
C. -2^31 to 2^31.
D. -2^32 to 2^32.

View Answer

Ans : C

Explanation: The range of integers must lie between -2^31 to 2^31.

5. How many value does Boolean data type hold?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : B

Explanation: Boolean: Hold only two values, either TRUE or FALSE.

6. Objects are defined as instances of user defined classes that can hold ____________?

A. values
B. functions
C. both values and functions
D. None of the above

View Answer

Ans : C

Explanation: Objects are defined as instances of user-defined classes that can hold both
values and functions.

7. What will be the output of the following PHP code?

<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>

A. This condition is TRUE


B. This condition is not TRUE
C. No Output
D. Error

View Answer

Ans : A

Explanation: This condition is TRUE is the output of the following PHP code.

8. What will be the output of the following PHP code?

<?php
$lfc = NULL;
echo $lfc;
?>

A. 0
B. Null
C. No Output
D. Error

View Answer

Ans : C

Explanation: The output of the following PHP code is no output.

9. What will be the output of the following PHP code?

<?php
$x1 = 10.58;
$x2 = 21.18;

$sum = $x1 + $x2;

echo $sum;
?>

A. 31
B. 32
C. 31.00
D. 31.76

View Answer

Ans : D

Explanation: 31.76 is the output of the following code.

10. What will be the output of the following PHP code?

<?php
$intArray = array( 10, 20 , 30);

echo "First Element: $intArray[3]


";
?>

A. First Element: 10
B. First Element: 20
C. First Element: 30
D. First Element:

View Answer

Ans : D

Explanation: As the third index is not available in $intArray so, the output is First Element:

1. PHP supports ____ types of looping techniques?

A. 2
B. 3
C. 4
D. 5

View Answer

Ans : C

Explanation: PHP supports four types of looping techniques.

2. How many main parameter are used in for loop?

A. 2
B. 3
C. 4
D. 1

View Answer

Ans : B

Explanation: There are three main parameters to the code, namely the initialization, the test
condition and the counter.

3.  do-while loop is an _____ control loop ?

A. exit
B. exist
C. easy
D. entry

View Answer

Ans : A

Explanation: The do-while loop is an exit control loop which means that it first enters the
loop, executes the statements, and then checks the condition.

4. while loop is an _____ control loop ?

A. exit
B. exist
C. easy
D. entry

View Answer

Ans : D

Explanation: The while loop is also an entry control loop i.e., it first checks the condition at
the start of the loop and if it is true then it enters the loop.

5. foreach loop is used to iterate over ____?

A. number
B. object
C. function
D. array
View Answer

Ans : D

Explanation: for each loop: This loop is used to iterate over the array. For every counter of
the loop, an array element is assigned and the next counter is shifted to the next element.

6. Which loop evaluates the condition expression as Boolean, if it is true, it executes the
statements and when it is false it will terminate?

A. For loop
B. while loop
C. do-while loop
D. All of the above

View Answer

Ans : B

Explanation: While loop evaluates the condition expression as Boolean, if it is true, it


executes the statements and when it is false it will terminate.

7. What will be the output of the following PHP code?

<?php

for ($num = 1; $num <= 10; $num += 2) {


echo "$num ";
}

?>

A. 1 3 5 7 9
B. 1 2 3 4 5
C. 9 7 5 3 1
D. Error

View Answer

Ans : A

Explanation: the output of the following PHP code 1 3 5 7 9.

8. What will be the output of the following PHP code?


<?php
$num = 20;

while ($num < 12) {


$num += 2;
echo $num, "\n";
}
?>

A. Error
B. No Output
C. infinite loop
D. Only one garbage value

View Answer

Ans : B

Explanation: The output of the following PHP code is no output.

9. What will be the output of the following PHP code?

<?php
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 0);
?>

A. Error
B. No Output
C. infinite loop
D. 4

View Answer

10. What will be the output of the following PHP code?

<?php
$arr = array (10, 20, 30);
foreach ($arr as $val) {
echo "$val1 \n";
}
?>

A. 10 20 30
B. No Output
C. 10
D. undefined variable

View Answer

Ans : D

Explanation: undefined variable $var1 will be the output of the following PHP code.

1. How many types of functions are available in php?

A. 5
B. 4
C. 3
D. 2

View Answer

Ans : D

Explanation: PHP provides us with two major types of functions Built-in functions and User
Defined Functions.

2. Which of the following is not a built-in function in php ?

A. print_r()
B. fopen()
C. fclosed()
D. gettype()

View Answer

Ans : C

Explanation: fclosed() is not a built-in function in php.

3. Why should we use functions?

A. Reusability
B. Easier error detection
C. Easily maintained
D. All of the above

View Answer

Ans : D
Explanation: we use functions beacause it provide Reusability, Easier error detection, Easily
maintained.

4. A function name always begins with the keyword _________.

A. fun
B. def
C. function
D. None of the above

View Answer

Ans : C

Explanation: A function name always begins with the keyword function.

5. A function name cannot start with a ____

A. alphabet
B. underscore
C. number
D. Both C and B

View Answer

Ans : C

Explanation: A function name cannot start with a number. It can start with an alphabet or
underscore.

6. A function name is not case-sensitive?

A. True
B. False
C. Only user-defined function is case-sensitive
D. None of the above

View Answer

Ans : A

Explanation: A function name is not case-sensitive, the following statement is true.


7. A function name is not case-sensitive?

<?php

function funclfc()
{
echo "This is letsfindcourse";
}

// Calling the function


funclfc();

?>

A. This is lfc
B. This is letsfindcourse
C. No Output
D. Error

View Answer

Ans : B

Explanation: The output of the following PHP code This is letsfindcourse.

8. A function name is not case-sensitive?

<?php

function prolfc($num1, $num2, $num3)


{
$mul = $num1 * $num2 * $num3;
echo "The product is $mul";
}

prolfc(1, 2, 3, 4);

?>

A. 24
B. 8
C. 6
D. Error: to many argument.

View Answer

Ans : C

Explanation: The output of the following PHP code is 6.


9. Type Hinting was introduced in which version of PHP?

A. PHP 5.1
B. PHP 5
C. PHP 5.3
D. PHP 5.4

View Answer

Ans : B

Explanation: PHP 5 introduced the feature of type hinting. With the help of type hinting, we
can specify the expected data type of an argument in a function declaration.

10. A function in PHP which starts with double underscore is known as __________.

A. Magic Function
B. Inbuilt Function
C. Default Function
D. User Defined Function

View Answer

Ans : A

Explanation: PHP functions that start with a double underscore - a "__" are called magic
functions in PHP.

1. How many types of array are available in php?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : C

Explanation: There are basically three types of arrays in PHP: Indexed or Numeric Arrays,
Associative Arrays, Multidimensional Arrays

2. By default, the index of array in php starts from ______?


A. 0
B. 1
C. -1
D. 2

View Answer

Ans : A

Explanation: By default, the index starts from zero.

3. A ________ is an array with more than two dimensions.

A. single dimensional array


B. multi dimensional array
C. Both A and B
D. None of the above

View Answer

Ans : B

Explanation: A multidimensional array is an array with more than two dimensions. In a


matrix, the two dimensions are represented by rows and columns

4. Which of the following are correct ways of creating an array?


i) arr[0] = "letsfindcourse";
ii) $arr[] = array("letsfindcourse");
iii) $arr[0] = "letsfindcourse";
iv) $arr = array("letsfindcourse");

A. ii), iii) and iv)


B. ii) and iii)
C. Only i)
D. iii) and iv)

View Answer

Ans : D

Explanation: A variable name should start with $ symbol which is not present in i) and you
need not put the square brackets when you use the array(), constructor.

5. Which in-built function will add a value to the end of an array?


A. array_unshift()
B. into_array()
C. inend_array()
D. array_push()

View Answer

Ans : D

Explanation: array_push adds value to the end of an array, returning the total count of
elements in the array after the new value has been added.

6. Which function returns an array consisting of associative key/value pairs?

A. count()
B. array_count()
C. array_count_values()
D. count_values()

View Answer

Ans : C

Explanation: The function array_count_values() will count all the values of an array.

7. What will be the output of the following PHP code?

<?php
$arr = array ("lets", "find", "course", ".Com");
echo (array_search (".com", $arr) );
?>

A. 0
B. Garbage value
C. 3
D. No Output

View Answer

Ans : D

Explanation: Due to case-sensitive .com is not in an array so there will be no output.

8. As compared to associative arrays vector arrays are much


A. Faster
B. Slower
C. Stable
D. None of the above

View Answer

Ans : A

Explanation: As compared to associative arrays vector arrays are much Faster.

9. What is the output of the following php code?

<?php
$alphabet = array ("A", "B", "C");
echo (next($alphabet));
?>

A. A
B. B
C. C
D. Error

View Answer

Ans : B

Explanation: The next function is an in-built function used to print the next value of the
current index. As the current index value is 0 so next will print value B.

10. What is the output of the following php code?

<?php
$alphabet = array("A" => array
( "php" => "php 7.0", "date" => "3 December 2019"),
"B" => array( "python" => "python 3.8.2",
"date" => "24 December 2019") );
echo $alphabet ["A"]["date"];
?>

A. php 7.0
B. 3 December 2019
C. python 3.8.2
D. 24 December 2019

View Answer

Ans : B
Explanation: The output of the following PHP code is 3 December 2015.

1. In how many ways we can create strings in PHP?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : B

Explanation: There are two ways of creating strings in PHP: single quote and double quote

2. Which type of string can processes special characters inside quotes?

A. single quote string


B. double quote string
C. Both A and B
D. None of the above

View Answer

Ans : B

Explanation: double-quote strings in PHP is capable of processing special characters.

3. Which of the following is not a Built-in String functions in php?

A. strlen()
B. str_replace()
C. strpos()
D. strreverse()

View Answer

Ans : D

Explanation: strreverse() function is not a Built-in String functions in php.

4. Why trim() function is used in php?


A. to remove whitespaces
B. to remove lowercase alphabet
C. to remove uppercase alphabet
D. to remove underscore

View Answer

Ans : A

Explanation: This trim() function allows us to remove whitespaces or strings from both sides
of a string.

5. Which of the following is the output of the below code?

<?php

echo strpos("Hello letsfindcourse!", "lets"), " \n";

?>

A. 4
B. 5
C. 6
D. 7

View Answer

Ans : C

Explanation: 6 is the output of the following code.

6. Which of the following is the output of the below code?

<?php

var_dump(strpos("Hello letsfindcourse!", "course"));

?>

A. int(13)
B. char(14)
C. int(14)
D. int(15)

View Answer

Ans : C
Explanation: int(14) is the output of the following code.

7. Which is true about var_dump() function?

A. var_dump() loops infinitely


B. var_dump() cuts off loop afetr getting same element two times
C. var_dump() cuts off loop after getting the same element three times
D. var_dump() cuts off loop after getting the same element five times

View Answer

Ans : C

Explanation: var_dump() cuts off loop after getting the same element three times is true about
var_dump() function.

8. The ________ function compares the two strings s1 and s2, ignoring the case of the
characters.

A. strtolower()
B. toLowerCase()
C. strcasecmp()
D. lc()

View Answer

Ans : C

Explanation: The strcasecmp() function compares the two strings s1 and s2, ignoring the case
of the characters.

9. Returns a string arguments with trilling blank space removed, is a behavior of

A. starts( ) function
B. chop( ) function
C. rtrim( ) function
D. lc()

View Answer

Ans : D

Explanation: Returns a string arguments with trilling blank space removed, is a behavior of
chop ( ) function and rtrim ( ) function
10. What is the output of the following php code?

<?php
$username = "letsfindcourse";
if (preg_match("([^a-z])",$username))
echo "Name must be all lowercase!";
else
echo "Name is all lowercase!";
?>

A. Error
B. No Output
C. Name must be all lowercase!
D. Name is all lowercase!

View Answer

Ans : D

Explanation: The name is all lowercase! is the output of the following PHP code.

1. Objects are also known as ______.

A. reference
B. template
C. class
D. instances

View Answer

Ans : D

Explanation: We define a class once and then make many objects that belong to them.
Objects are also known as instances.

2. Object are created using ____ keyword?

A. create
B. object
C. new
D. None of the above

View Answer

Ans : C

Explanation: The object is created using the new keyword


3. A member function typically accesses members of _____ object only

A. current
B. previous
C. next
D. All of the above

View Answer

Ans : A

Explanation: After creating our objects, we can call member functions related to that object.
A member function typically accesses members of a current object only.

4. Constructor is also called ____ function

A. find
B. key
C. automatic
D. magic

View Answer

Ans : D

Explanation: A constructor is also called magic function because, in PHP, magic methods
usually start with two underscore characters.

5. Which of the following is the output of the below code?

<?php
class letsfindcourse
{
public $lfc_name = "letsfindcourse";

public function __construct($lfc_name)


{
$this->lfc_name = $lfc_name;
}
}

$lfc = new letsfindcourse("letsfindcourse");


echo $lfc->lfc_name;

?>
A. letsfindcourse
B. 1
C. Error
D. No Output

View Answer

Ans : A

Explanation: letsfindcourse is the output of the following code.

6. Which of the following is the output of the below code?

<?php
class lfc {

var $mcq_type;

function setmcq_type($par){
$this->mcq_type = $par;
}

function getmcq_type(){
echo $this->mcq_type."<br>";
}

$obj = new lfc;

$obj->setmcq_type("Objects Mcq");
$obj->getmcq_type();
?>

A. Objects Mcq
B. Objects Mcq ""
C. Error
D. No Output

View Answer

Ans : B

Explanation: Objects Mcq<br> is the output of the following code.

7. PHP recognizes constructors by the name.


A. classname()
B. _construct()
C. function _construct()
D. function __construct()

View Answer

Ans : D

Explanation: A double underscore followed by the construct keyword. Its syntax is function
__construct ([ argument1, argument2,.....]) { Class Initialization code }

8. Which one of the following functions is used to determine object type?

A. obj_type()
B. type()
C. is_a()
D. is_obj()

View Answer

Ans : C

Explanation: The is_a() function returns true if the object belongs to a class type or if it
belongs to a class that is a child of that class. Or else false is returned.

9.  Which one of the following can be used to instantiate an object in PHP assuming class
name to be LFC?

A. $obj = new $LFC;


B. $obj = new LFC;
C. $obj = new LFC ();
D. obj = new LFC ();

View Answer

Ans : C

Explanation: $obj = new foo (); can be used to instantiate an object in PHP assuming class
name to be LFC

10. In the PHP code given below, what is/are the properties?

<?php
class letsfindcourse
{
public $name;
function lfc()
{
echo "This is an Object Mcq";
}
}
?>

A. echo “This is an Object Mcq”;


B. public $name;
C. class letsfindcourse
D. function lfc()

View Answer

Ans : B

Explanation: Yes, they are nothing but variables.

1. Classes are the _______ of objects.

A. type
B. blueprints
C. reference
D. instances

View Answer

Ans : B

Explanation: Classes are the blueprints of objects.

2. Class is a programmer-defined data type, which includes _____ methods and ______
variable?

A. local, global
B. global, global
C. global, local
D. local, local

View Answer

Ans : D

Explanation: Class is a programmer-defined data type, which includes local methods and
local variables.
3. What will be the syntax of defining the class?

A. class lfc ()
B. class lfc []
C. class lfc {}
D. lfc class{}

View Answer

Ans : C

Explanation: class lfc {} be the syntax of class.We enclose a class using curly braces ( { } )
… just like you do with functions.

4. We define our own class by starting with the keyword ______ ?

A. class
B. function
C. auto
D. var

View Answer

Ans : A

Explanation: We define our own class by starting with the keyword class.

5. Which of the following is the output of the below code?

<?php
class letsfindcourse
{

public function __construct(){


echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}

$lfc = new letsfindcourse;


?>

A. The class letsfindcourse was initiated!<br>


B. The class lfc was initiated!<br>
C. Error
D. No Output
View Answer

Ans : A

Explanation: The class letsfindcourse was initiated!<br> is the output of the following code.

6. Which of the following is the output of the below code?

<?php
class letsfindcourse
{

public function __destruct(){


echo 'The class "' . __CLASS__ . '" was destroyed!';
}

$lfc = new letsfindcourse;


?>

A. The class letsfindcourse was destroyed!


B. The class lfc was initiated!
C. Error
D. No Output

View Answer

Ans : A

Explanation: The class letsfindcourse was destroyed! is the output of the following code.

7. Which one of the following functions is used to determine whether a class exists?

A. exist()
B. exist_class()
C. class_exist()
D. __exist()

View Answer

Ans : C

Explanation: The class_exist() function returns true or false according to whether the class
exists within the currently executing script content.
8. Which keyword is used to refer to properties or methods within the class itself?

A. Private
B. public
C. Protected
D. this

View Answer

Ans : D

Explanation: this keyword is used to refer to properties or methods within the class itself.

9. Which one of the following is the right way to call a class constant, given that the class is
mathFunction?

A. echo mathFunction->PI;
B. echo PI;
C. echo mathFunction::PI;
D. echo mathFunction=PI;

View Answer

Ans : C

Explanation: echo mathFunction::PI; is the right way to call a class constant, given that the
class is mathFunction

10. The class from which the child class inherits is called


(i) Child class
(ii) Parent class
(iii) Super class
(iv) Base class

A. Only (i)
B. (ii), (iii) and (iv)
C. Only (iii)
D. (ii) and (iv)

View Answer

Ans : D

Explanation: The class from which the child class inherits is called Parent class and Base
class.
1. In Which php version Exception handling was added?

A. PHP 5.1
B. PHP 5.2
C. PHP 5.3
D. PHP 5

View Answer

Ans : D

Explanation: Exception handling was added to PHP with the version 5 release, and further
enhanced with version 5.3.

2. How many methods are available for the exception class?

A. five
B. six
C. seven
D. eight

View Answer

Ans : C

Explanation: The seven methods are: getCode(), getFile(), getLine(), getMessage(),


getPrevious(), getTrace(), getTraceAsString().

3. what is try block do?

A. It represent block of code in which exception can arise.


B. It is used in place of catch block or after catch block .
C. It is used to throw an exception.
D. None of the above

View Answer

Ans : A

Explanation: try: It represent block of code in which exception can arise.

4. what is finally block do?


A. It represent block of code in which exception can arise.
B. It is used in place of catch block or after catch block .
C. It is used to throw an exception.
D. None of the above

View Answer

Ans : B

Explanation: finally: It is used in place of catch block or after catch block basically it is put
for cleanup activity in PHP code.

5. what is throw block do?

A. It represent block of code in which exception can arise.


B. It is used in place of catch block or after catch block .
C. It is used to throw an exception.
D. None of the above

View Answer

Ans : C

Explanation: throw: It is used to throw an exception. It is also used to list the exceptions that
a function throws, but doesn’t handle itself.

6. Which of the following statements invoke the exception class?

A. throws new Exception();


B. throw new Exception();
C. new Exception();
D. new throws Exception();

View Answer

Ans : B

Explanation: throw new Exception(); trigger an exception and each “throw” must have
at least one “catch”.

7. Why Exception Handling in PHP used?

A. Separation of error handling code from normal code


B. Grouping of error types
C. Both A And B
D. None of the above

View Answer

Ans : C

Explanation: Exception Handling in PHP used for Separation of error handling code from
normal code and Grouping of error types.

8. Which of the following is not specialized keywords in exception handling.

A. try
B. catch
C. throw
D. this

View Answer

Ans : D

Explanation: this keyword is not specialized keywords in exception handling.

9. How many error levels are available in PHP?

A. 14
B. 15
C. 16
D. 17

View Answer

Ans : C

Explanation: There are 16 error levels available in PHP.

10. What is the description of Error level E_ERROR?

A. Fatal run-time error


B. Near-fatal error
C. Compile-time error
D. Fatal Compile-time error

View Answer
Ans : A

Explanation: A Fatal run-time error is the description of Error level E_ERROR.

You might also like