Вы находитесь на странице: 1из 18

1.

Difference between echo and print


The only differences are as follows:
1. echo does not return a value whereas print does return a value of 1 (this enables print to be
used in expressions).
2. echo can accept multiple parameters (although such usage is rare) while print can only take a
single argument.

2.Print and print_r


print_r() is used for printing the array in human readable format. The difference between
echo, print, print_r and var_dump is very simple. echo is actually not a function but a language
construct which is used to print output. It is marginally faster than the print.

3.cookies and session


A session in PHP is maintained at server whereas a cookie is saved at client's browser. ... The main
difference between session and cookie is that cookies are stored on user's computer in the text file
format while sessions are stored on the server side.

4. Implode() and explode()


The implode() function returns a string from the elements of an array. Note: Theimplode() function
accept its parameters in either order. However, for consistency with explode(), you should use the
documented order of arguments. Note: The separator parameter of implode() is optional.

5. session_destroy and unset()


session_destroy() destroys all of the data associated with the current session. It does not unset any of
the global variables associated with the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.

6.Include() and require


Difference between require and include: If a required file is not found PHP will emit a fatal error whereas
for include only a warning will be emitted. include() will throw a warning if it can't include the file, but
the rest of the script will run.

7. String comparison using == vs strcmp() in PHP


The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two
inputs to compare and returns true value if both of the values are same (It compares only value of
variable, not data types) and returns false value if both of the values are not same.
The strcmp() is an inbuilt function in PHP which is used to compare two strings. This function is case-
sensitive which points that capital and small cases will be treated differently, during comparison. This
function compares two strings and tells whether the first string is greater or smaller or equals to the
second string.

8. How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators
differ?
The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two
inputs to compare and returns true value if both of the values are same (It compares only value of
variable, not data types) and return a false value if both of the values are not same.
The comparison operator called as the Identical operator is the triple equal sign “===”. This operator
allows for a much stricter comparison between the given variables or values.This operator returns true if
both variables contains same information and same data types otherwise return false.
9. What is PEAR in php?
PEAR (PHP Extension and Application Repository) is a framework and repository for reusable PHP
components. PEAR is a code repository containing all kinds of php code snippets and libraries.
PEAR also offers a command-line interface that can be used to automatically install packages.

10. What is use of the header() function in PHP?


1. header() is used to redirect from one page to another: header("Location: index.php");
2. header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");
3. header() is used to send a raw HTTP header: header('Content-Type: application/json');

11. What is the difference between include_once() and require_once() , which one would you use in
circumstances where you need to connect to a database, and why?
include_once() or include allows a file to be included, and in cases where the file is missing or has the
wrong name, we receive an error message and execution will still continue regardless.
On the other hand, require_once() or require would be suitable in cases where a file needs to be
included once and if it is missing or has a wrong name then we receive a fatal error and the execution of
the program stops.
require_once or require is a suitable method in cases where a database connection file is involved and
helps alleviate the possibility of multiple instances of the same file being included several times.

PHP Interview Questions


1) What is PHP?

PHP stands for Hypertext Preprocessor. It is an open source server-side scripting


language which is widely used for web development. It supports many databases
like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.
More Details...

2) What is PEAR in PHP?

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.

3) Who is known as the father of PHP?

Rasmus Lerdorf

4) What was the old name of PHP?

Personal Home Page.

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

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.
6) What is the name of scripting engine in PHP?

The Zend Engine is the open source scripting engine written in C language that
interprets the PHP programming language.

7) Explain the difference between PHP4 and PHP5.

PHP4 doesn't support oops concept and uses Zend Engine 1.


PHP5 supports oops concept and uses Zend Engine 2.

8) What are the popular Content Management Systems (CMS) in PHP?

o WordPress
o Joomla
o Magento
o Drupal etc.

9) What are the popular frameworks in PHP?

o CakePHP
o CodeIgniter
o Yii 2
o Symfony
o Zend Framework etc.

10) Which programming language does PHP resemble to?

PHP has borrowed its syntax from Perl and C.

12) What is "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. It returns nothing.

13) What is "print" in PHP?

PHP print output a string. It is a language construct not a function. So use of


parentheses is not required with the argument list. Unlike echo, it always returns 1.

14) What is the difference between "echo" and "print" in PHP?

Echo can output one or more string but print can only output one string and
always returns 1.
Echo is faster than print because it does not return any value.

15) How a variable is declared in PHP?

PHP variable is a name of memory location that holds data. It is a temporary


storage.
Syntax:
$variableName=value;

16) 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.

17) 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:
o Using define() function
o Using const() function

18) What are magic constants in PHP?

PHP magic constants are predefined constants which changes on the basis of their
use. They start with a double underscore (__) and end with a double underscore
(__).

19) How many data types are there in PHP?

PHP data types are used to hold different types of data or values. There are 8
primitive data types which are further categorized in 3 types:
PHP Data Types
1. Scalar Types
2. Compound Types
3. Special Types
PHP Data Types: Scalar Types

There are 4 scalar data types in PHP.


1. boolean
2. integer
3. float
4. string
PHP Data Types: Compound Types

There are 2 compound data types in PHP.


1. array
2. object
PHP Data Types: Special Types

There are 2 special data types in PHP.


1. resource
2. NULL

20) How to do single and multi line comment in PHP?

PHP single line comment is done in two ways:


o Using // (C++ style single line comment)
o Using # (Unix Shell style single line comment)
PHP multi line comment is done by enclosing all lines within /* */.

21) What are the different loops in PHP?

For, while, do-while and for each.

22) 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.

23) What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be
called before sending the actual output. For example, you can't print any HTML
element before using this function.

24) What does isset() function?

The isset() function checks if the variable is defined and not null.

25) Explain PHP parameterized functions.

PHP parameterized functions are functions with parameters. You can pass any
number of parameters inside a function. These passed parameters act as variables
inside your function. They are specified inside the parentheses, after function
name. Output depends upon dynamic values passed as parameters into function.

26) Explain PHP variable length argument function

PHP supports variable length argument function. It means you can pass 0, 1 or n
number of arguments in function. To do this, you need to use 3 ellipses (dots)
before the argument name. The 3 dot concept is implemented for variable length
argument since PHP 5.6.

27) Explain PHP variable length argument function.

PHP supports variable length argument function. It means you can pass 0, 1 or n
number of arguments.

28) What is the array in PHP?

PHP array is an ordered map (contains value on the basis of key). It is used to hold
multiple values of similar type in a single variable.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.


Easy to traverse: By the help of single loop, we can traverse all the elements of
an array.
Sorting: We can sort the elements of array.
PHP Array Types

There are 3 types of array in PHP.


1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an index
number by default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example

File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
Click me for more details...

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example

File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

29) How many types of array are there in PHP?

There are three types of array in PHP:


o Indexed array
o Associative array
o Multidimensional array

30) Explain some of the PHP array functions?

There are many array functions in PHP:


o array()
o array_change_key_case()
o array_chunk()
o count()
o sort()
o array_reverse()
o array_search()
o array_intersect()

31) What is the difference between indexed and associative array?

The indexed array holds elements in an indexed form which is represented by


number starting from 0 and incremented by 1. For example:
$season=array("summer","winter","spring","autumn");
The associative array holds elements with name. For example:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

32) How to get the length of string?

The strlen() function is used to get the length of string.

33) Explain some of the PHP string functions?

There are many array functions in PHP:


o strtolower()
o strtoupper()
o ucfirst()
o lcfirst()
o ucwords()
o strrev()
o strlen()

34) What are the methods to submit form in PHP?

There are two methods GET and POST.

35) How can you submit a form without a submit button?

You can use JavaScript submit() function to submit the form without explicitly
clicking any submit button.

36) What are the ways to include file in PHP?

PHP allows you to include file so that page content can be included in another PHP
file. There are two ways to include file in PHP.
1. Include()
2. Require()

37) Differentiate between require and include?

Require and include both are used to include a file, but if file is not found include
sends warning and continues executing the script whereas require sends Fatal error
and stops the execution.

38) Explain setcookie() function in PHP?

PHP setcookie() function is used to set cookie with HTTP response. Once cookie is
set, you can access it by $_COOKIE superglobal variable.
Syntax:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

39) How can you retrieve a cookie value?

echo $_COOKIE ["user"];


More Details...
40) What is a session?

PHP Engine creates a logical object to preserve data across subsequent HTTP
requests or multiple pages of the same application, which is known as session.
Sessions generally store temporary data to allow multiple PHP pages to offer a
complete functional transaction for the same user.
Simply, it maintains data of a user (browser).

41) What is the method to register a variable into a session?

<?php
Session_register($ur_session_var);
?>

42) What is $_SESSION in PHP?

PHP $_SESSION is an associative array that contains all session variables. It is


used to set and get session variable values.

43) What is PHP session_start() and session_destroy() function?

PHP session_start() function is used to start the session. It starts a new or resumes
the existing session. It returns the existing session if session is created already. If
session is not available, it creates and returns new sessions.

44) What is the difference between session and cookie?

The main difference between session and cookie is that cookies are stored on
user's computer in the text file format while sessions are stored on the server side.
Cookies can't hold multiple variables on the other hand Session can hold multiple
variables.
You can manually set an expiry for a cookie, while session only remains active as
long as browser is open.

45) Write syntax to open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. It accepts
two arguments: $filename and $mode.
Syntax:
1. resource fopen ( string $filename , string $mode [, bool $use_include_path =
false [, resource $context ]] )

46) 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:
o fread()
o fgets()
o fgetc()
47) How to write in a file in PHP?

PHP fwrite() and fputs() functions are used to write data into file. To write data into
file, you need to use w, r+, w+, x, x+, c or c+ mode.

48) How to delete file in PHP?

The unlink() function is used to delete file in PHP.


bool unlink (string $filename)

49) What is the method to execute a PHP script from the command line?

You should just run the PHP command line interface (CLI) and specify the file
name of the script to be executed.

50) How to upload file in PHP?

The move_uploaded_file() function is used to upload file in PHP.


bool move_uploaded_file ( string $filename , string $destination )

51) How to download file in PHP?

The readfile() function is used to download file in PHP.


int readfile ( string $filename )

52) How can you send email in PHP?

The mail() function is used to send email in PHP.


bool mail($to,$subject,$message,$header);

53) How do you connect MySQL database with PHP?

There are two methods to connect MySQL database with PHP. Procedural and
object oriented style.

54) How to create connection in PHP?

The mysqli_connect() function is used to create connection in PHP.


resource mysqli_connect (server, username, password)

55) How to create database connection and query in PHP?

Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use following 2
alternatives.
o mysqli_query()
o PDO::_query()

56) How can we increase execution time of a PHP script?

By default, maximum execution time for PHP scripts is set to 30 seconds. If a script
takes more than 30 seconds, PHP stops the script and returns an error.
You can change the script run time by changing the max_execution_time directive
in php.ini file.
When a script is called, set_time_limit function restarts the timeout counter from
zero. It means, if default timer is set to 30 sec, and 20 sec is specified in function
set_time_limit(), then script will run for 45 seconds. If 0 sec is specified in this
function, script takes unlimited time.

57) What are the different types of errors in PHP?

There are 3 types of error in PHP.


Notices:These are non-critical errors. These errors are not displayed to the users.
Warnings:These are more serious errors but they do not result in script
termination. By default, these errors are displayed to the user.
Fatal Errors:These are the most critical errors. These errors may cause due to
immediate termination of script.

58) How to stop the execution of PHP script?

The exit() function is used to stop the execution of PHP script.

59) What are the encryption functions in PHP?

CRYPT() and MD5()

60) What is htaccess in PHP?

The .htaccess is a configuration file on Apache server. You can change


configuration settings using directives in Apache configuration files like .htaccess
and httpd.conf.

61) Explain PHP explode() function.

The PHP explode() function breaks a string into an array.

62) Explain PHP split() function.

The PHP split() function splits string into an array by regular expression.

63) How can we get IP address of a client in PHP?

$_SERVER["REMOTE_ADDR"];

https://www.javatpoint.com/php-interview-questions

PHP STRING FUNTIONS


chr() It is used to return a character from a specified ASCII value.

chunk_split() It is used to split a string into a series of smaller parts.

echo() It is used for output one or more strings.


explode() It is used to break a string into an array.

print() It is used for output one or more strings.

fprint() It is used to write a formatted string to a stream.

Implode() It is used to return a string from the elements of an array.

Lcfirst() It is used to convert the first character of a string to lowercase.

Join() It is the Alias of implode() function.

trim() It is used to remove whitespace.

ltrim() It is used to remove whitespace from the left side of a string.

rtrim() It is used to remove whitespace from the right side of a string.

money_format() It is used to return a string formatted as a currency string.

printf() It is used to show output as a formatted string.

sscanf() It is used to parse input from a string according to a format.

str_repeat() It is used to repeat a string a specified number of times.

str_split() It is used to split a string into an array.

str_word_count() It is used to count the number of words in a string.

strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a string inside another


string.

strcmp() It is binary safe string comparison.

strlen() It is used to return the length of a string.

strncmp() It is used to compare of the first n characters.

strpos() It is used to return the position of the first occurrence of a string


inside another string.

strrchr() It is used to find the last occurrence of a string inside another


string.

strrev() It is used to reverse a string.

1) PHP strtolower() function


The strtolower() function returns string in lowercase letter.
Syntax
string strtolower ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
Output:
my name is khan

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.
Syntax
string strtoupper ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS KHAN

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.
Syntax
string ucfirst ( string $str )
Example
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is KHAN

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't
change the case of other characters.
Syntax
string lcfirst ( string $str )
Example
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
echo $str;
?>
Output:
mY name IS KHAN
5) PHP ucwords() function
The ucwords() function returns string converting first character of each word into
uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
Output:
My Name Is Sonoo Jaiswal

6) PHP strrev() function


The strrev() function returns reversed string.
Syntax
string strrev ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:
lawsiaj oonoS si eman ym

7) PHP strlen() function


The strlen() function returns length of the string.
Syntax
int strlen ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>
Output:
24
Function Description Example Output
strtolower Used to convert all string echo outputs benjamin
characters to lower case strtolower( 'Benjamin');
letters
strtoupper Used to convert all string echo strtoupper('george outputs GEORGE W
characters to upper case w bush'); BUSH
letters
strlen The string length function is echo strlen('united 24
used to count the number of states of america');
character in a string. Spaces
in between characters are
Function Description Example Output
also counted
explode Used to convert strings into an $settings = explode(';', Array ( [0] =>
array variable "host=localhost; host=localhost [1] =>
db=sales; uid=root; db=sales [2] =>
pwd=demo"); uid=root [3] =>
print_r($settings); pwd=demo )
substr Used to return part of the $my_var = 'This is a This is a re...
string. It accepts three (3) really long sentence that
basic parameters. The first I wish to cut short';echo
one is the string to be substr($my_var,0,
shortened, the second 12).'...';
parameter is the position of
the starting point, and the third
parameter is the number of
characters to be returned.
str_replace Used to locate and replace echo str_replace ('the', that laptop is very
specified string values in a 'that', 'the laptop is very expensive
given string. The function expensive');
accepts three arguments. The
first argument is the text to be
replaced, the second
argument is the replacement
text and the third argument is
the text that is analyzed.
strpos Used to locate the and return echo strpos('PHP 4
the position of a character(s) Programing','Pro');
within a string. This function
accepts two arguments
sha1 Used to calculate the SHA-1 echo sha1('password'); 5baa61e4c 9b93f3f0
hash of a string value 682250b6cf8331b
7ee68fd8
md5 Used to calculate the md5 echo md5('password'); 9f961034ee 4de758
hash of a string value baf4de09ceeb1a75
str_word_coun Used to count the number of echo str_word_count 12
t words in a string. ('This is a really long
sentence that I wish to
cut short');
ucfirst Make the first character of a echo ucfirst('respect'); Outputs Respect
string value upper case
lcfirst Make the first character of a echo lcfirst('RESPECT'); Outputs rESPECT
string value lower case

String manipulation in PHP


Defining Strings
In PHP, we can define string in multiple ways. Lets discuss them one by one:
1.Single Quote Strings
We can declare strings using single quotes. When we use single quotes to
define a string and print them, PHP interpreter does not parse the string and
print it as it is. Consider:
$many = 9;
$sentence = 'Our solar system contains $many planets';
print $sentence;
Output:
Our solar system contains $many planets
2.Double Quote Strings
PHP also allows declaring strings in double quotes. At the time of printing of
a double quote string, it is parsed and if there are any variables, they are
replaced. Consider:
$many = 9;
$sentence = "Our solar system contains $many planets";
print $sentence;
Output:
Our solar system contains 9 planets
3.heredoc
Heredoc method of defining string in PHP is used when we have very complex
strings.
The heredoc supports all the features of double quotes. It also allows strings to
be defined in more than one line without string concatenation.
We use heredoc syntax when there is a complex string spread over multiple
lines. In this syntax, we may use double quotes inside the string sequence
without escaping them.
Example:
$name = "Bootsity";

$here_doc = <<<EOT
This is $name website
for PHP, Laravel and Angular Tutorials

EOT;

echo $here_doc;
Output:
This is Bootsity website
for PHP, Laravel and Angular Tutorials
4.nowdoc
The Nowdoc string definition method in PHP is like the heredoc method but it
works like the way single quotes work.
For nowdoc, no parsing takes place at time of printing inside the Nowdoc
blocks.
Nowdoc string definition comes handy when we are working with raw data that
do not need to be parsed.
Consider:
$name = "Bootsity";

$here_doc = <<<'EOT'
This is $name website
for PHP, Laravel and Angular Tutorials

EOT;

echo $here_doc;
Output:
This is $name website
for PHP, Laravel and Angular Tutorials

Concatenating strings
In PHP, string concatenation is done using concatenation operator, which is
denoted by a dot (.)
Lets see how we can use it practically:
$str = "Bootsity"." Tutorials"
echo $str; // will print - Bootsity Tutorials
Some important String functions
In this section, we are including most frequently used in-built PHP functions
related to strings. If you want to see the complete list of string functions,
1 strtolower
strtolower makes a string lowercase
print strtolower("PHP and Laravel Tutorials"); // php and laravel
tutorials
Similarly, to make a string uppercase, we can use strtoupper
2 strlen
strlen computes length of string
print strlen("abcd"); // 4
3 explode
explode returns array after separating strings delimited by given string
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
4 substr
substr returns part of the string
$rest = substr("abcdef", 0, -1); // returns "abcde"
$rest = substr("abcdef", 2, -1); // returns "cde"
$rest = substr("abcdef", 4, -4); // returns false
5 ucfirst
ucfirst turns a string’s first character uppercase
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
5. Comments
Comments are strings that we write in our programs to give information
about the current code. Comments are meta-data about code and are not
executed at run-time. PHP supports two type of comments: 1. Single line
comments and 2. Multi line comments. Let’s see them:
<?php

/* Multiline comment
it spreads across multiple lines
*/

// Single line comment

# another syntax for single line comment


?>
https://www.afterhoursprogramming.com/tutorial/php/php-overview/

Вам также может понравиться