PHP INTERVIEW QUESTIONS ANSWERS

What is PHP?
PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning
What is the use of “echo” in php?
PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required.
Syntax:
- void echo ( string $arg1 [, string $… ] )
What is the difference between == and === operator in PHP ?
In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.
Example Usages:
<?php $a=true ; $b=1; // Below condition returns true and prints a and b are equal if($a==$b){ echo "a and b are equal"; }else{ echo "a and b are not equal"; } //Below condition returns false and prints a and b are not equal because $a and $b are of different data types. if($a===$b){ echo "a and b are equal"; }else{ echo "a and b are not equal"; } ?>
What does PEAR stand for?
- PEAR means “PHP Extension and Application Repository”. It extends PHP and provides a higher level of programming for web developers.
What is the difference between GET and POST?
- GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
- GET can handle a maximum of 2048 characters, POST has no such restrictions.
- GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
- Normally GET is used to retrieve data while POST to insert and update.
Understanding the fundamentals of the HTTP protocol is very important to have for a PHP developer, and the differences between GET and POST are an essential part of it.
What is session in PHP. How to remove data from a session?
As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages PHP session are used. PHP sessions are the simple way to store data for individual users/client against a unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data, if session id is not present on server PHP creates a new session, and generate a new session ID.
Example Usage:-
<?php // starting a session session_start(); // Creating a session $_SESSION['user_info'] = ['user_id' =>1,
'first_name' => 'Ramesh', 'last_name' => 'Kumar', 'status' => 'active']; // checking session if (isset($_SESSION['user_info'])) { echo "logged In"; } // un setting remove a value from session unset($_SESSION['user_info']['first_name']); // destroying complete session session_destroy(); ?>
How to register a variable in PHP session ?
In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we can set directly a value in $_SESSION Global.
Example usage:
<?php // Starting session session_start(); // Use of session_register() is deprecated $username = "PhpScots"; session_register("username"); // Use of $_SESSION is preferred $_SESSION["username"] = "PhpScots"; ?>
What’s the difference between include and require?
If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
require_once(), require(), include().What is difference between them?
require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the “function re-declared” error.
What is the difference between Session and Cookie?
The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
How to create a mysql connection?
mysql_connect(servername,username,password);
What is the difference between $message and $$message?
$message stores variable data while $$message is used to store variable of variables.
$message stores fixed data whereas the data stored in $$message may be changed dynamically.
What are the ways to define a constant in PHP?
PHP constants are name or identifier that can’t be changed during execution of the script. PHP constants are defined in two ways:
- Using define() function
- Using const() function
How to execute an sql query? How to fetch its result ?
$my_qry = mysql_query(“SELECT * FROM `users` WHERE `u_id`=’1′; “);
$result = mysql_fetch_array($my_qry);
echo $result[‘First_name’];
What are PHP Magic Methods/Functions. List them.
In PHP all functions starting with __ names are magical functions/methods. Magical methods always lives in a PHP class.The definition of magical function are defined by programmer itself.
Here are list of magic functions available in PHP
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() .
What is difference between include,require,include_once and require_once() ?
Include :-Include is used to include files more than once in single PHP script.You can include a file as many times you want.
Syntax:- include(“file_name.php”);
Include Once:-Include once include a file only one time in php script.Second attempt to include is ignored.
Syntax:- include_once(“file_name.php”);
Require:-Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.
Syntax:- require(“file_name.php”);
Require Once :-Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.
Syntax:- require_once(“file_name.php”);
What is the use of explode() function ?
Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.
What is the difference between explode() and split() functions?
Split function splits string into array by regular expression. Explode splits a string into array by string.
What are constructor and destructor in PHP ?
PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed.
Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class .
Here is sample class with constructor and destructer in PHP.
<?php class Foo { private $name; private $link; public function __construct($name) { $this->name = $name; } public function setLink(Foo $link){ $this->link = $link; } public function __destruct() { echo 'Destroying: ', $this->name, PHP_EOL; } } ?>
What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?
mysql_fetch_assoc function Fetch a result row as an associative array, Whilemysql_fetch_array() fetches an associative array, a numeric array, or both
How to do single and multi line comment in PHP?
PHP single line comment is done in two ways:
- Using // (C++ style single line comment)
- Using # (Unix Shell style single line comment)
PHP multi line comment is done by enclosing all lines within /* */.
What is the use of “ksort” in php?
It is used for sort an array by key in reverse order
What are the different errors in PHP?
In PHP, there are three types of runtime errors, they are:
Warnings:
These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
Notices:
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
Fatal errors:
These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.
What are the different loops in PHP?
For, while, do-while and for each.
What is the use of count() function in PHP?
The PHP count() function is used to count total elements in the array, or something an object.
What does isset() function?
The isset() function checks if the variable is defined and not null.
List data types in PHP ?
PHP supports 9 primitive types
4 scalar types:
- integer
- boolean
- float
- string
3 compound types:
- array
- object
- callable
And 2 special types:
- resource
- NULL
What is difference between strstr() and stristr() ?
In PHP both functions are used to find the first occurrence of substring in a string except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then FALSE will be returned.
Sample Usage:
<?php $email = ‘abc@xyz.com’; $hostname = strstr($email, ‘@’); echo $hostname; output: @xyz.com stristr() does the same thing in Case-insensitive manner ?>
How many types of array are there in PHP?
There are three types of array in PHP:
- Indexed array
- Associative array
- Multidimensional array
Explain some of the PHP array functions?
There are many array functions in PHP:
- array()
- array_change_key_case()
- array_chunk()
- count()
- sort()
- array_reverse()
- array_search()
- array_intersect()
Explain some of the PHP string functions?
There are many array functions in PHP:
- strtolower()
- strtoupper()
- ucfirst()
- lcfirst()
- ucwords()
- strrev()
- strlen()
How to read a file in PHP?
PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.
PHP file read functions are given below:
- fread()
- fgets()
- fgetc()
How can you send email in PHP?
The mail() function is used to send email in PHP.
- bool mail($to,$subject,$message,$header);
Explain preg_Match and preg_replace?
These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to work with other regular functions.
preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with string, it returns true otherwise it returns false.
Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in the string and if pattern matched, ten replace that match with the specified pattern
What is php.ini & .htacess file?
Both are used to make the changes to your PHP setting. These are explained below:
php.ini: It is a special file in PHP where you make changes to your PHP settings. It works when you run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting by editing a php.ini file or, making a new text file and save it as php.ini.
.htaccess: It is a special file that you can use to manage/change the behavior of your site. It works when PHP is installed as an Apache module. These changes include such as redirecting your domain’s page to https or www, directing all users to one page, etc.