PHP Interview Questions & Answers for Freshers

PHP interview questions for freshers: what PHP is, data types, variables, operators, strings, arrays, include vs require, GET vs POST, cookies, sessions and file basics.

What is PHP?

PHP (PHP: Hypertext Preprocessor) is a popular, free and open-source server-side scripting language. It is mostly used to create websites and web applications. PHP code runs on the server, and the visitor gets only the result as HTML.

With PHP you can create static and dynamic websites, handle forms, work with cookies and sessions, send emails, read and write files, and connect with databases like MySQL.

<?php
echo "Hello, World!";
?>

Output:

Tutorials Class - Output Window

Hello, World!

PHP powers WordPress and many other big websites. The current series is PHP 8. Start learning in the PHP Introduction, and see the full form of PHP also.

Who is the father of PHP?

Rasmus Lerdorf is known as the father of PHP. He created it in 1994 as a set of small CGI programs, written in the C language, to track the visitors of his online resume. The first public release came in 1995.

In 1997 two developers, Zeev Suraski and Andi Gutmans, rewrote the core of the language. Their work became PHP 3, and later they built the Zend Engine (the name comes from the first letters of Zeev and Andi) that is the base of PHP from PHP 4 until today.

Read more in the PHP Introduction.

What is the correct & common way to start and finish a PHP block of code?

The correct and recommended way is the standard tags: <?php to start and ?> to finish.

<?php
echo "Hello from standard tags";
?>

Output:

Tutorials Class - Output Window

Hello from standard tags

There is also the short echo tag <?= ... ?>. It prints a value and it is always available (PHP 5.4 and above), so it is good inside HTML.

<p>Year: <?= date("Y") ?></p>
  • The old short open tag <? ... ?> works only when short_open_tag is On in php.ini. It is usually Off, so do not use it.
  • In a file that has only PHP code, leave out the closing ?> tag. It avoids problems with extra spaces after it.

See also PHP Syntax.

What is Open Source Software?

Open source software is software whose source code is made available to everyone. Anyone can see the code, use the software, change it, and share it with others, under the rules of its license.

Examples: PHP, MySQL, WordPress, Linux, Apache and Git.

  • Free to start: most open source tools do not cost anything.
  • Safer and better: many people check the code and find the bugs.
  • No lock-in: you can change the software or move your data when you want.
  • Big community: you get help, plugins and tutorials easily.
Note: Open source does not always mean free of cost for every use, and every project has a license (like GPL or MIT) with rules. Read the license before you use or sell something built with it.

Is PHP a case sensitive language?

Partly. In PHP, variable names are case-sensitive, but function names, class names and keywords are not.

Case-sensitiveNot case-sensitive
Variable names ($name and $Name are different)Keywords like echo, if, while, function
Constants (created with define or const)Function names (sum() and SUM() are same)
Array keys (“Name” and “name” are different)Class names and method names
<?php
$name = "James";

ECHO $name . "<br>";     // keywords are not case-sensitive

function sum() {
    return "Function called";
}

echo SUM();              // same as sum()
?>

Output:

Tutorials Class - Output Window

James
Function called

If you write echo $NAME;, PHP shows a warning “Undefined variable $NAME”, because it is a different variable.

Note: Even if PHP allows it, write function and class names in the same case as they were created. It keeps the code clean. See PHP Syntax.

What is the default extension of the PHP file?

The default extension of a PHP file is .php, for example index.php. The web server sends every file with this extension to PHP, which runs the code and sends the result to the browser.

You may see .phtml or .php5 in some old projects, but today .php is used everywhere.

Note: Never save PHP files like config or include files as .inc or .txt. The server does not run them, so a visitor can open them in the browser and read your code and passwords. Always use .php.

What is PHP Function?

A function is a block of statements that does one specific job. It can take values as input (parameters), do some work and give back a result. You write it once and call it whenever you need.

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(5, 3);
?>

Output:

Tutorials Class - Output Window

8

PHP has many built-in functions (like strlen()) and you can also create your own with the function keyword. Learn more in PHP Functions.

What are the form method Attribute available for submitting?

The method attribute of the HTML <form> tag tells how the form data is sent to the server. There are two values: GET and POST. If you write nothing, the default is GET.

<form method="get" action="search.php">
    <!-- fields -->
</form>

<form method="post" action="login.php">
    <!-- fields -->
</form>
GETPOST
Data goes in the URL (visible)Data goes in the request body (not in the URL)
PHP reads it from $_GETPHP reads it from $_POST
Use for search and filtersUse for login, registration and changes

The details are in difference between GET and POST and PHP Forms Handling.

What are the different PHP functions to sort an array?

PHP has many functions to sort an array. Choose one by asking: do you sort by value or by key, in which order, and do you need to keep the keys?

FunctionSortsKeeps keys?
sort()Values, low to highNo
rsort()Values, high to lowNo
asort()Values, low to highYes
arsort()Values, high to lowYes
ksort()Keys, low to highYes
krsort()Keys, high to lowYes
usort()Values using your own functionNo
uasort() / uksort()Values / keys using your own functionYes

For text with numbers like “img2” and “img10”, natsort() gives a natural order. Here is a custom sort with usort().

<?php
$people = [["Anil", 30], ["Robin", 25], ["Zoya", 22]];

usort($people, fn($a, $b) => $a[1] <=> $b[1]);   // by age

echo $people[0][0];
?>

Output:

Tutorials Class - Output Window

Zoya

See more examples in PHP Array Functions and ksort().

What is include() function in PHP?

The include statement takes all the code of another file and adds it to the current file, at the place where you write it. It is used to reuse parts like a header, a menu or a footer.

<?php
include "header.php";

echo "<p>Page content</p>";

include "footer.php";
?>

If the file is missing, include gives a warning, but the script continues. Related statements are include_once, require and require_once. See include() vs require() and PHP File Inclusion.

What are the different types of error in PHP?

PHP has four main types of errors at run time, plus deprecated messages.

TypeMeaningStops the script?
Parse errorWrong syntax, like a missing semicolon or bracketYes, nothing runs
Fatal errorA serious problem, like calling a function that does not existYes
WarningA problem, but PHP can go on, like a missing include fileNo
NoticeA small problem, like using an undefined variable (in PHP 8 this is a warning)No
DeprecatedYou use a feature that will be removed in futureNo

In PHP 7 and above many fatal errors are thrown as Error objects, so you can catch them. Learn how to show, hide and handle errors in PHP Errors.

PHP’s numerically indexed array begins with which position?

A numerically indexed array in PHP begins with position 0, not 1. The first element has the key 0, the second has 1, and so on.

<?php
$array = [15, 80, 67, 33];

echo $array[0] . "<br>";
echo $array[3];
?>

Output:

Tutorials Class - Output Window

15
33

This array has 4 elements, so the keys are 0, 1, 2 and 3. If you try $array[4], PHP shows a warning “Undefined array key 4”, because there is no element at that position. The last key is always count($array) - 1.

Which PHP function inserts an element to the end of an array?

Use array_push() to add one or more elements to the end of an array. A shorter way for one element is $array[] = value.

<?php
$fruits = ["Apple", "Banana"];

array_push($fruits, "Mango", "Orange");
$fruits[] = "Grapes";

print_r($fruits);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
[4] => Grapes
)

To add an element at the start use array_unshift(). To remove the last or the first element use array_pop() and array_shift(). See PHP Array Functions.

Why we use PHP String functions trim(), ltrim() and rtrim()?

These functions remove white spaces (or other characters that you give) from the ends of a string. They are useful to clean the input of a form.

FunctionRemoves from
trim()Both sides
ltrim()Left side (start)
rtrim()Right side (end)
<?php
echo "[" . trim("  Welcome  ") . "]<br>";
echo trim("--Hello--", "-") . "<br>";
echo ltrim("007", "0") . "<br>";
echo rtrim("Hello!!!", "!");
?>

Output:

Tutorials Class - Output Window

[Welcome]
Hello
7
Hello

The second parameter is a list of characters to remove. If you skip it, PHP removes spaces, tabs, new lines and a few more invisible characters. These functions do not remove spaces from the middle of a string, see how to remove all white spaces.

Which PHP function can be used check if variable is an array?

Use the is_array() function. It returns true if the variable is an array and false if it is not.

<?php
var_dump(is_array([1, 2, 3]));
var_dump(is_array("Hello"));
var_dump(is_array(null));
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)
bool(false)

There are similar functions for other types, like is_string(), is_int() and is_bool(). See how to check the data type of a variable.

What PHP Function is used to find position of a string?

Use the strpos() function. It returns the position of the first occurrence of a text inside a string, or false if the text is not found. The counting starts from 0.

<?php
echo strpos("I like apple and banana", "apple");
?>

Output:

Tutorials Class - Output Window

7

The word “apple” starts at position 7, because “I like ” has 7 characters (0 to 6). Because the result can be 0 for a match at the start, always check with !== false. Learn more in PHP strpos() Function and how to check if a string contains a substring.

How many types of arrays are available in PHP?

There are three types of arrays in PHP.

TypeKeysExample
Indexed arrayNumbers, from 0["Apple", "Banana"]
Associative arrayNames that you choose["name" => "Robin", "age" => 25]
Multidimensional arrayAn array inside an array[[1, 2], [3, 4]]
<?php
$indexed = ["Apple", "Banana"];
$assoc = ["name" => "Robin", "age" => 25];
$multi = [[1, 2], [3, 4]];

echo $indexed[1] . "<br>";
echo $assoc["name"] . "<br>";
echo $multi[1][0];
?>

Output:

Tutorials Class - Output Window

Banana
Robin
3

Learn all of them with examples in PHP Arrays.

What is the use of ucwords() PHP String function?

ucwords() changes the first letter of each word of a string to a capital letter. The rest of the letters are not changed.

<?php
echo ucwords("hello world from php") . "<br>";

// Different word separator
echo ucwords("hello-world foo", "-") . "<br>";

// Make the other letters small first
echo ucwords(strtolower("PHP TUTORIAL"));
?>

Output:

Tutorials Class - Output Window

Hello World From Php
Hello-World foo
Php Tutorial

By default words are separated by a space, tab or new line. Use the second parameter to give your own separators. To change only the first letter of the whole string use ucfirst().

What is the use of array_chunk() function in PHP?

array_chunk() splits an array into smaller arrays (chunks) of the size that you give. The syntax is array_chunk(array, size, preserve_keys).

<?php
$numbers = [1, 2, 3, 4, 5];

echo json_encode(array_chunk($numbers, 2)) . "<br>";

$data = ["a" => 1, "b" => 2, "c" => 3];
echo json_encode(array_chunk($data, 2, true));
?>

Output:

Tutorials Class - Output Window

[[1,2],[3,4],[5]]
[{“a”:1,”b”:2},{“c”:3}]

The last chunk can be smaller. By default the keys are not kept, pass true as the third parameter to keep them. It is useful to show items in rows or to process a big array in parts.

What is the use of str_replace() PHP String function?

str_replace() searches a string for some text and replaces it with new text. It replaces all matches.

<?php
echo str_replace("Hello", "Hi", "Hello World, Hello PHP");
?>

Output:

Tutorials Class - Output Window

Hi World, Hi PHP

It is case-sensitive. For a case-insensitive replace use str_ireplace(). See more examples in how to replace a part of a string in PHP.