PHP - Interview Questions
Dear readers, these PHP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of PHP. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
Following are the common usage of PHP −
- PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
- PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user.
- You add, delete, modify elements within your database thru PHP.
- Access cookies variables and set cookies.
- Using PHP, you can restrict users to access some pages of your website.
- It can encrypt data.
All PHP code must be included inside one of the three special markup tags ate are recognised by the PHP Parser.
<?php PHP code goes here ?> <? PHP code goes here ?> <script language="php"> PHP code goes here </script>
Most common tag is the <?php...?>
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version. If your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP.'
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters.
Yes!
Here are the most important things to know about variables in PHP −
- All variables in PHP are denoted with a leading dollar sign ($).
- The value of a variable is the value of its most recent assignment.
- Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
- Variables can, but do not need, to be declared before assignment.
- Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.
- Variables used before they are assigned have default values.
- PHP does a good job of automatically converting types from one to another when necessary.
- PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −
- Integers − are whole numbers, without a decimal point, like 4195.
- Doubles − are floating-point numbers, like 3.14159 or 49.1.
- Booleans − have only two possible values either true or false.
- NULL − is a special type that only has one value: NULL.
- Strings − are sequences of characters, like 'PHP supports string operations.'
- Arrays − are named and indexed collections of other values.
- Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
- Resources − are special variables that hold references to resources external to PHP (such as database connections).
Rules for naming a variable are following −
- Variable names must begin with a letter or underscore character.
- A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc.
Here are the rules for determine the "truth" of any value not already of the Boolean type −
- If the value is a number, it is false if exactly equal to zero and true otherwise.
- If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
- Values of type NULL are always false.
- If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
- Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
- Don't use double as Booleans.
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties −
- It evaluates to FALSE in a Boolean context.
- It returns FALSE when tested with IsSet() function.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.
As indicated by the name, this function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.
constant() example
<?php define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
- There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
- Constants cannot be defined by simple assignment, they may only be defined using the define() function.
- Constants may be defined and accessed anywhere without regard to variable scoping rules.
- Once the Constants have been set, may not be redefined or undefined.
PHP provides a large number of predefined constants to any script which it runs known as magic constants.
_LINE_ : The current line number of the file.
_FILE_ : The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
_FUNCTION_ : The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_CLASS_ : The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_METHOD_ : The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
break terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
continue causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value) { code to be executed; }
Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices.
To concatenate two string variables together, use the dot (.) operator:
<?php $string1="Hello World"; $string2="1234"; echo $string1 . " " . $string2; ?>
This will produce following result:
Hello World 1234
The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!":
<?php echo strlen("Hello world!"); ?>
This will produce following result:
12
The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string:
<?php echo strpos("Hello world!","world"); ?>
This will produce following result:
6
PHP provides a function getenv() to access the value of all the environment variables.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.
The PHP rand() function is used to generate a random number. This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifiies the seed number as its argument.
The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called.
The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading.
The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.
The HTTP header will be different from the actual header where we send Content-Type as text/html\n\n. In this case content type will be application/octet-stream and actual file name will be concatenated alongwith it.
For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.
#!/usr/bin/perl # HTTP Header print "Content-Type:application/octet-stream; name=\"FileName\"\r\n"; print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n"; # Actual File Content open( FILE, "<FileName" ); while(read(FILE, $buffer, 100) ) { print("$buffer"); }
The PHP provides $_GET associative array to access all the sent information using GET method.
The PHP provides $_POST associative array to access all the sent information using POST method.
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
array() − Creates an array.
array_change_key_case() − Returns an array with all keys in lowercase or uppercase.
array_chunk() − Splits an array into chunks of arrays.
array_count_values() − Returns an array with the number of occurrences for each value.
array_diff() − Compares array values, and returns the differences.
array_diff_assoc() − Compares array keys and values, and returns the differences.
array_diff_key() − Compares array keys, and returns the differences.
array_fill() − Fills an array with values.
array_fill_keys() − Fill an array with values, specifying keys.
array_flip() − Exchanges all keys with their associated values in an array.
array_intersect() − Compares array values, and returns the matches.
array_intersect_assoc() − Compares array keys and values, and returns the matches.
array_intersect_key() − Compares array keys, and returns the matches.
array_key_exists() − Checks if the specified key exists in the array.
array_keys() − Returns all the keys of an array.
array_merge() − Merges one or more arrays into one array.
array_pop() − Deletes the last element of an array.
array_push() − Inserts one or more elements to the end of an array.
array_rand() − Returns one or more random keys from an array.
array_reduce() − Returns an array as a string, using a user-defined function.
array_reverse() − Returns an array in the reverse order.
array_search() − Searches an array for a given value and returns the key.
array_shift() − Removes the first element from an array, and returns the value of the removed element.
array_slice() − Returns selected parts of an array.
array_sum() − Returns the sum of the values in an array.
array_splice() − Removes and replaces specified elements of an array.
array_udiff() − Compares array values in a user-made function and returns an array.
array_udiff_assoc() − Compares array keys, and compares array values in a user-made function, and returns an array.
array_udiff_uassoc() − Compares array keys and array values in user-made functions, and returns an array.
array_uintersect() − Compares array values in a user-made function and returns an array.
array_uintersect_assoc() − Compares array keys, and compares array values in a user-made function, and returns an array.
array_uintersect_uassoc() − Compares array keys and array values in user-made functions, and returns an array.
array_unique() − Removes duplicate values from an array.
array_unshift() − Adds one or more elements to the beginning of an array.
array_values() − Returns all the values of an array.
array_walk() − Applies a user function to every member of an array.
array_walk_recursive() − Applies a user function recursively to every member of an array.
arsort() − Sorts an array in reverse order and maintain index association.
asort() − Sorts an array and maintain index association.
compact() − Create array containing variables and their values.
count() − Counts elements in an array, or properties in an object.
current() − Returns the current element in an array.
each() − Returns the current key and value pair from an array.
end() − Sets the internal pointer of an array to its last element.
extract() − Imports variables into the current symbol table from an array.
in_array() − Checks if a specified value exists in an array.
key() − Fetches a key from an array.
krsort() − Sorts an array by key in reverse order.
ksort() − Sorts an array by key.
natcasesort() − Sorts an array using a case insensitive "natural order" algorithm.
natsort() − Sorts an array using a "natural order" algorithm.
next() − Advances the internal array pointer of an array.
prev() − Rewinds the internal array pointer.
range() − Creates an array containing a range of elements.
reset() − Sets the internal pointer of an array to its first element.
rsort() − Sorts an array in reverse order.
shuffle() − Shuffles an array.
sort() − Sorts an array.
uasort() − Sorts an array with a user-defined function and maintain index association.
uksort() − Sorts an array by keys using a user-defined function.
usort() − Sorts an array by values using a user-defined function.
What is Next ?
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
No comments:
Post a Comment