All PHP Interview Questions & Answers

All PHP interview questions with simple answers. Covers variables, operators, strings, arrays, functions, loops, OOP, file handling, MySQL, security, sessions and new PHP 8 features.

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.

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

in_array() checks if a value exists in an array. It returns true if the value is found, and false if not.

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

var_dump(in_array("Banana", $fruits));
var_dump(in_array("Mango", $fruits));

// Third parameter true = check the data type also
var_dump(in_array("1", [1, 2, 3]));
var_dump(in_array("1", [1, 2, 3], true));
?>

Output:

Tutorials Class - Output Window

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

By default in_array() compares loosely, so the string “1” matches the number 1. Pass true as the third parameter for a strict comparison. To get the position of the value, use array_search(), and to check a key use array_key_exists().

Which PHP function counts all the values of an array?

array_count_values() counts how many times each value appears in an array. It returns a new array where the values become keys and the counts become values.

<?php
$fruits = ["apple", "banana", "apple", "orange", "apple"];

print_r(array_count_values($fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[apple] => 3
[banana] => 1
[orange] => 1
)

It works only with strings and integers. If you only need the total number of elements, use count().

What is the latest version of PHP?

The current series of PHP is PHP 8. At the time of writing (November 2026) the latest stable branch is PHP 8.5. A new minor version (8.x) comes out every year, near the end of November.

Do not depend on a number written in an article, because it gets old. The official pages show the truth: php.net for the latest release, and php.net/supported-versions.php for the versions that still get fixes.

  • Old versions like PHP 5 and 7 do not get security fixes anymore, so a website on them is not safe.
  • You can see the version of your own server with echo PHP_VERSION; or php -v.
  • Read what changed in PHP 8 in new features of PHP 8.
Note: Before you upgrade a live website, test it on a copy. Old plugins and old code can break on a new PHP version.

How can we submit a form without a submit button?

A form can be sent with JavaScript, without a submit button. Use the submit() method of the form, for example from a link click or when a select box changes.

<form id="myForm" method="post" action="process.php">
    <input type="text" name="name" value="Robin">
</form>

<a href="#" onclick="document.getElementById('myForm').submit(); return false;">Send the form</a>
<select onchange="this.form.submit()" name="city" form="myForm">
    <option>Delhi</option>
    <option>Mumbai</option>
</select>

PHP receives the data in the normal way, from $_POST. See PHP Forms Handling.

Note: Do not name any form field “submit” or “action”. It hides the form method and submit() stops working. Also remember that submit() skips the HTML validation, use requestSubmit() if you want the browser to check the fields first.

Can we include a file two times in any PHP page?

Yes, you can use include (or require) for the same file many times. PHP will add its code every time.

But there is a problem if that file declares a function or a class. The second include tries to create the same function again, and PHP stops with a fatal error like “Cannot redeclare function”.

<?php
include "helpers.php";
include "helpers.php";        // error if helpers.php has functions

include_once "helpers.php";   // safe: adds the file only one time
?>

Use include_once or require_once for files with functions, classes or settings. They check if the file was already added. See PHP File Inclusion.

Difference Between Cookies and Session

Both cookies and sessions remember information about a visitor, but they keep it in different places.

CookieSession
Stored inThe visitor browserThe server
Size limitAbout 4 KBNo fixed limit (depends on the server)
Visible to the userYes, the user can read and change itNo, only the session id is in the browser
LifetimeUntil the expiry date you setUntil the browser is closed or the session expires (about 24 minutes of inactivity by default)
Best forSmall, harmless data: theme, language, “remember me” tokenPrivate data: login status, user id, shopping cart
PHP array$_COOKIE$_SESSION

A session actually uses a cookie too, but only for the session id (called PHPSESSID). PHP uses that id to find the real data on the server. So the private data never goes to the browser.

<?php
// Cookie: stored in the browser
setcookie("theme", "dark", time() + 3600);

// Session: stored on the server
session_start();
$_SESSION["user_id"] = 25;
?>
Note: Do not store passwords or private data in cookies, because the user can change them. Learn more in PHP Cookies and PHP Session.

What is the full form of PHP?

The full form of PHP is PHP: Hypertext Preprocessor.

When Rasmus Lerdorf created it in 1994, it was a set of small tools for his personal website, so the name meant Personal Home Page. Later the name was changed. PHP is called a recursive acronym, because the first letter P of the short form stands for PHP itself.

Start learning in the PHP Introduction chapter.

How to find String Length in PHP?

Use the strlen() function. It returns the length of a string. Spaces and special characters are counted too.

<?php
echo strlen("Hello world!");
?>

Output:

Tutorials Class - Output Window

12

strlen() counts bytes, so for non-English text (like Hindi) or emoji use mb_strlen(). See strlen() vs mb_strlen().

Which is the PHP function to delete a file from server?

Use the unlink() function. It deletes a file from the server and returns true on success. It is better to check first if the file exists.

<?php
$file = "sample-file.txt";

if (file_exists($file) && unlink($file)) {
    echo "File deleted";
} else {
    echo "File not found or could not be deleted";
}
?>

Output:

Tutorials Class - Output Window

File deleted

  • The deleted file can not be taken back.
  • PHP needs permission to delete the file, otherwise you get a warning.
  • Never pass a file name from user input without checking it.
  • Do not mix it with unset(), see unlink() vs unset().

How can we create a session in php?

A PHP session stores information about a user on the server, so you can use it on many pages. Start it with session_start() and save the data in the $_SESSION array.

<?php
// page1.php
session_start();

$_SESSION["username"] = "Robin";

echo "Session created.";
?>
<?php
// page2.php
session_start();

echo "Hello " . $_SESSION["username"];
?>

Output:

When page2.php is opened after page1.php

Hello Robin

Call session_start() at the top of every page that uses the session, before any output. Read PHP Session for login examples and security.

What is PHP floor() function?

The floor() function rounds a number down to the next lower whole number. It always returns a float.

<?php
echo floor(7.8) . "<br>";
echo floor(-3.2) . "<br>";
var_dump(floor(5.9));
?>

Output:

Tutorials Class - Output Window

7
-4
float(5)

Notice that floor(-3.2) is -4, because -4 is lower than -3.2. The related functions are ceil() (round up) and round() (round to the nearest). Use intdiv() for whole number division.

How can we remove the white spaces from string in PHP?

It depends on which spaces you want to remove.

NeedFunction
Remove spaces from both endstrim()
Remove spaces from the left side onlyltrim()
Remove spaces from the right side onlyrtrim()
Remove all spaces everywherestr_replace(" ", "", $text)
Remove spaces, tabs and new lines everywherepreg_replace("/\s+/", "", $text)
<?php
echo "[" . trim("  Hello PHP  ") . "]<br>";
echo str_replace(" ", "", "a b c") . "<br>";
echo preg_replace('/\s+/', '', " a \n b\tc ");
?>

Output:

Tutorials Class - Output Window

[Hello PHP]
abc
abc

The trim functions can also remove other characters, see why we use trim(), ltrim() and rtrim().

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

Both functions read one row from a MySQL result, but the format of the row is different.

FunctionReturns the row asHow to read a value
mysqli_fetch_array()An array with both numeric and column-name keys$row["name"] or $row[0]
mysqli_fetch_object()An object, columns are properties$obj->name
mysqli_fetch_assoc()An array with column-name keys only$row["name"]

The examples use the users table of our MySQL chapters. Suppose the user with id 1 is Ram.

<?php
require_once('db-connection.php');

$sql = "SELECT name, email FROM users WHERE id = 1";

$row = mysqli_fetch_array(mysqli_query($conn, $sql));
echo $row["name"] . " / " . $row[1] . "<br>";

$obj = mysqli_fetch_object(mysqli_query($conn, $sql));
echo $obj->name . " / " . $obj->email;
?>

Output:

Tutorials Class - Output Window

Ram / ram@example.com
Ram / ram@example.com

In the first line, $row[1] is the second column (email), because the numeric keys start from 0. Most developers prefer mysqli_fetch_assoc(), because it does not keep every value two times. See all the options in ways to fetch data from a result set.

How to count the number of parameters passed in a PHP function?

Use func_num_args() inside the function. It returns how many arguments were passed. func_get_args() returns them in an array.

<?php
function total() {
    return func_num_args();
}

echo total(10, 20, 30);
?>

Output:

Tutorials Class - Output Window

3

In modern PHP the clearer way is a variadic parameter (...$args), and then count($args).

<?php
function total(...$args) {
    return count($args);
}

echo total(10, 20, 30);
?>

Output:

Tutorials Class - Output Window

3

Learn more in PHP Functions.

How can you pass a variable by reference in PHP?

Write an ampersand (&) before the parameter in the function. Then the function works on the original variable, not on a copy.

Normally PHP passes arguments by value. If the function changes the value, the variable outside does not change. With a reference it does.

<?php
function add_line(&$line) {
    $line .= " and extra words added.";
}

$sample = "This is a sample line,";
add_line($sample);

echo $sample;
?>

Output:

Tutorials Class - Output Window

This is a sample line, and extra words added.

Without the &, the output would be only “This is a sample line,”. Objects are different: PHP passes the handle of an object, so a function can change its properties without any ampersand.

Note: Use references only when you really need them, because they make the code harder to follow. Often it is cleaner to return the new value from the function. See PHP Functions.