PHP( Hyper Text Processor)

1) What is PEAR in PHP?

Ans) PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries.

It also provides a command line interface to install "packages" automatically.

2) Explain the difference b/w static and dynamic websites?

Ans) In static websites, content can't be changed after running the script. You can't change anything in the site. It is predefined.

In dynamic websites, content of script can be changed at the run time. Its content is regenerated every time a user visit or reload. Google, yahoo and every search engine is the example of dynamic website.

3) Is multiple inheritance supported in PHP?

Ans) PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword ‘extended’.

4) What is the meaning of a final class and a final method?

Ans) ‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overridden.

5) How is the comparison of objects done in PHP?

Ans) We use the operator ‘==’ to test is two objects are instanced from the same class and have same attributes and equal values. We can test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.

6) What type of operation is needed when passing values through a form or an URL?

Ans) If we would like to pass values through a form or an URL, then we need to encode and to decode them using htmlspecialchars() and urlencode().

7) How can PHP and Javascript interact?

Ans)PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

8) What is the use of the function ‘imagetypes()’?

Ans) imagetypes() gives the image format and types supported by the current version of GD-PHP.

9) What are the functions to be used to get the image’s properties (size, width, and height)?

Ans) The functions are getimagesize() for size, imagesx() for width and imagesy() for height.

10) How failures in execution are handled with include() and require() functions?

Ans) If the function require() cannot access the file then it ends with a fatal error. However, the include() function gives a warning, and the PHP script continues to execute.

11) What is the main difference between require() and require_once()?

Ans) require(), and require_once() perform the same task except that the second function checks if the PHP script is already included or not before executing it.

(same for include_once() and include())

12) How can we display information of a variable and readable by a human with PHP?

Ans) To be able to display a human-readable result we use print_r().

13) How is it possible to set an infinite execution time for PHP script?

Ans) The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini file.

14)How to call constructor of parent class?


15)What is use of var_dump?

Ans)It is used to display the data-type and values of variable. For Example.


16) What is final class?

Ans) It is class which can not be inherited.

Following are example of final class

final class baseclass{
public function testmethod() {
echo "base class method";

17) What does the PHP error ‘Parse error in PHP – unexpected T_variable at line x’ means?

Ans)This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.

18) What should we do to be able to export data into an Excel file?

Ans) The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as a separator between fields and then to open the file with Excel.

19) What is the function file_get_contents() useful for?

Ans) file_get_contents() lets reading a file and storing it in a string variable.

20) How can we connect to a MySQL database from a PHP script?

Ans) To be able to connect to a MySQL database, we must use mysqli_connect() function as follows:
$database = mysqli_connect("HOST", "USER_NAME", "PASSWORD"); mysqli_select_db($database,"DATABASE_NAME");

21) How be the result set of Mysql handled in PHP?

Ans) The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.

22) How is it possible to know the number of rows returned in the result set?

Ans) The function mysqli_num_rows() returns the number of rows in a result set.

23) Which function gives us the number of affected entries by a query?

Ans) mysqli_affected_rows() return the number of entries affected by an SQL query.

24) What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?

Ans) The mysqli_fetch_object() function collects the first single matching record where mysqli_fetch_array() collects all matching records from the table in an array.

25) How can we access the data sent through the URL with the GET method?

Ans) To access the data sent via the GET method, we use $_GET array like this:
$variable = $_GET["var"]; this will now contain 'value'

26) How can we access the data sent through the URL with the POST method?

Ans) To access the data sent this way, you use the $_POST array.

Imagine you have a form field called ‘var’ on the form when the user clicks submit to the post form, you can then access the value like this: $_POST["var"];

27) How can we check the value of a given variable is a number?

Ans) It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.

28) How can we check the value of a given variable is alphanumeric?

Ans) It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.

29) How do I check if a given variable is empty?

Ans) If we want to check whether a variable has a value or not, it is possible to use the empty() function.

30) What does the unlink() function mean?

Ans) The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.

31) What does the unset() function mean?

Ans) The unset() function is dedicated for variable management. It will make a variable undefined.

32) How do I escape data before storing it in the database?

Ans) The addslashes function enables us to escape data before storage into the database.

33) How is it possible to remove escape characters from a string?

Ans) The stripslashes function enables us to remove the escape characters before apostrophes in a string.

34) Is it possible to remove the HTML tags from data?

Ans) The strip_tags() function enables us to clean a string from the HTML tags.

35) what is the static variable in function useful for?

Ans) A static variable is defined within a function only the first time, and its value can be modified during function calls as follows:
function testFunction() {
static $testVariable = 1;
echo $testVariable;
//1 testFunction();
//2 testFunction();

36) How can we define a variable accessible in functions of a PHP script?

Ans) This feature is possible using the global keyword.

37) How is it possible to return a value from a function?

Ans) A function returns a value using the instruction ‘return $value;’.

38) What is the most convenient hashing method to be used to hash passwords?

Ans) It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. Hence, hashing passwords with these algorithms can create vulnerability.

39) Which cryptographic extension provide generation and verification of digital signatures?

Ans) The PHP-OpenSSL extension provides several cryptographic operations including generation and verification of digital signatures.

40) How is a constant defined in a PHP script?

Ans) The define() directive lets us defining a constant as follows: define ("ACONSTANT", 123);

41) How is the ternary conditional operator used in PHP?

Ans) It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows: Expression_1?Expression_2 : Expression_3;

42) What is the function func_num_args() used for?

Ans) The function func_num_args() is used to give the number of parameters passed into a function.

43) If the variable $var1 is set to 10 and the $var2 is set to the character var1, what’s the value of $$var2?

Ans) $$var2 contains the value 10.

44) What does accessing a class via :: means?

Ans) :: is used to access static methods that do not require object initialization.

45) In PHP, objects are they passed by value or by reference?

Ans)In PHP, objects passed by value.

46) Are Parent constructors called implicitly inside a class constructor?

Ans) No, a parent constructor have to be called explicitly as follows:


47) What’s the difference between __sleep and __wakeup?

Ans) __sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.

48) What is faster?


$variable1 = 'Hello '; $variable2 = 'World';
$variable3 = $variable1.$variable2;
1- $variable1 = 'Hello ';
$variable2 = 'World';
$variable3 = $variable1.$variable2;
2- $variable3 = "$variable1$variable2";

$variable3 will contain “Hello World”. The first code is faster than the second code especially for large large sets of data.

49) what is the definition of a session?

Ans) A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

50) How to initiate a session in PHP?

Ans) The use of the function session_start() lets us activating a session.

51) How can you propagate a session id?

Ans) You can propagate a session id via cookies or URL parameters.

52) What is the meaning of a Persistent Cookie?

Ans) A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.

53) When do sessions end?

Ans) Sessions automatically end when the PHP script finishes executing but can be manually ended using the session_write_close().

54) What is the difference between session_unregister() and session_unset()?

Ans) The session_unregister() function unregister a global variable from the current session and the session_unset() function frees all session variables.

55) What does $GLOBALS mean?

Ans) $GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.

56) What does $_SERVER mean?

Ans) $_SERVER is an array including information created by the web server such as paths, headers, and script locations.

57) What does $_FILES means?

Ans) $_FILES is an associative array composed of items sent to the current script via the HTTP POST method.

58) What is the difference between $_FILES[‘userfile’][‘name’] and $_FILES[‘userfile’][‘tmp_name’]?

Ans) $_FILES[‘userfile’][‘name’] represents the original name of the file on the client machine, $_FILES[‘userfile’][‘tmp_name’] represents the temporary filename of the file stored on the server.

59) How can we get the error when there is a problem to upload a file?

Ans) $_FILES[‘userfile’][‘error’] contains the error code associated with the uploaded file.

60) What does $_ENV mean?

Ans) $_ENV is an associative array of variables sent to the current PHP script via the environment method.

61) What does $_COOKIE mean?

Ans) $_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.

62) what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?

Ans) $a and $b: TRUE if both $a and $b are TRUE.

$a & $b: Bits that are set in both $a and $b are set.

63) What are the two main string operators?

Ans) The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is (‘.=’), which appends the argument on the right to the argument on the left.

64) What does the array operator ‘===’ means?

Ans) $a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

65) What is the differences between $a != $b and $a !== $b?

Ans) != means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).

66) How can we determine whether a PHP variable is an instantiated object of a certain class?

Ans) To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.

67) What is the goto statement useful for?

Ans) The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.

68) what is the difference between Exception::getMessage and Exception:: getLine?

Ans) Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.

69) What does the expression Exception::__toString means?

Ans) Exception::__toString gives the String representation of the exception.

70) How is it possible to parse a configuration file?

Ans) The function parse_ini_file() enables us to load in the ini file specified in filename and returns the settings in it in an associative array.

71) What is the difference between the functions strstr() and stristr()?

Ans) The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-sensitive.

stristr() is identical to strstr() except that it is case insensitive.

72) what is the difference between for and foreach?

Ans) for is expressed as follows:
for (expr1; expr2; expr3)
The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues, and the statements inside for are executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.

However, foreach provides an easy way to iterate over arrays, and it is only used with arrays and objects.

73) Is it possible to submit a form with a dedicated button?

Ans) It is possible to use the document.form.submit() function to submit the form. For example: onClick=”document.form.submit()

74) What is the difference between ereg_replace() and eregi_replace()?

Ans) The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.

75) Is it possible to protect special characters in a query string?

Ans) Yes, we use the urlencode() function to be able to protect special characters.

76) What are the three classes of errors that can occur in PHP?

Ans) The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors (critical errors).

77) How can we pass the variable through the navigation between the pages?

Ans) It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.

78) Is it possible to extend the execution time of a PHP script?

Ans) The use of the set_time_limit(int seconds) enables us to extend the execution time of a PHP script. The default limit is 30 seconds.

79) Is it possible to destroy a cookie?

Ans) Yes, it is possible by setting the cookie with a past expiration time.

80) What is the default session time in PHP?

Ans) The default session time in php is until the closing of the browser

81) Is it possible to use COM component in PHP?

Ans) Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.

82) Explain whether it is possible to share a single instance of a Memcache between multiple PHP projects?

Ans) Yes, it is possible to share a single instance of Memcache between multiple projects. Memcache is a memory store space, and you can run memcache on one or more servers. You can also configure your client to speak to a particular set of instances. So, you can run two different Memcache processes on the same host and yet they are completely independent. Unless, if you have partitioned your data, then it becomes necessary to know from which instance to get the data from or to put into.

83) Write a program for this pattern ?

* * * * *

* * * *

* * *

* *


Ans) for($i=0;$i<=5;$i++){
echo "* ";
echo "

84) Find last 4 letter of the string.?

Ans) $string = "Array99 has good blog for PHP programming";
$substring = substr($string, -4);
echo $substring; //Output: ming

85) Extract “good blog” from of below string.? Array99 has good blog for PHP programming.

Ans) $string = "Array99 has good blog for PHP programming.";
$extractWord = "good blog";
$substring = substr($string, strpos($string, $extractWord), strlen($extractWord));
echo $substring; //Output: good blog

86) Find the index of any element in an array.

Ans) $numbers = array(5, 3, 7, 9, 6, 8);
echo array_search(7, $numbers);
//Output: 2

87) What will be output of below code and why?

$string = "Array99 has good blog for PHP programming.";
$substr = "Array99";
if(strpos($string, $substr))
echo "found";
echo "not found";


Output will be “not found” because strpos($string, $substr) returns 0 as position and this is treated as false in IF condition. So the right code below.

$string = "Array99 has good blog for PHP programming.";
$substr = "Array99";
if(strpos($string, $substr) !== false)
echo "found";
echo "not found";

88) Check element in below array is an array or not.

Ans) $colors = array("red", "green", array("orange", "maroon"), "blue", "yellow", array("purple", "brown"));
foreach($colors as $c)
echo "This element is an array.";
echo "This element is not an array.";

89) Convert any name in an array.

Ans) $name = "sachin tendulkar";
$nameArray = array();
for($i = 0; $i $nameArray[] = $name[$i];
//Output: Array ( [0] => s [1] => a [2] => c [3] => h [4] => i [5] => n [6] => [7] => t [8] => e [9] => n [10] => d [11] => u [12] => l [13] => k [14] => a [15] => r )

90) How to create a text file in php?

Ans) $filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
echo ( "Error in opening new file" ); exit();
fwrite( $file, "This is a simple test\n" );
fclose( $file );

91)How to convert one date format into another in PHP ?

Ans) $old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);

92) Write a program to print the below format :

1 5 9

2 6 10

3 7 11

4 8 12

Ans) for($i=1;$i<=4;$i++) {
echo $i." ".$i1." ".$i2;
echo "

93) What would be the output of following:

Ans) $a = '1';
echo $b = &$a;
echo $c = "2$b";

94) How to scrape data from website using CURL?

Ans) To scrap the data from website, Website must be public and open for scrapable.

In the blow code, just update the CURLOPT_URL to which websites data you want to scrap.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
echo $output;

95) Explain the difference between $message and $$message?

Ans) $message is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.

$Message = "YOU"; $you= "Me";
echo $message //Output:- you
echo $$message //output :-Me

$$message allows the developer to change the name of the variable dynamically.

96) How to convert first letter of string to uppercase in php?

Ans) $string="cakephp and zend";
echo ucwords($string);

97) How to convert array to json in php?

Ans) $array = array('one','two');
echo json_encode($array); //use json_decode for decode

98)How to serialize an array in php?

Ans) $array = array('one','two');
echo serialize($array);//use unserialize for convert serialized string to array

99) How to get ip address in php?



100) How to count the number of elements in an array?


$array = array('cakephp','zend');