Basic PHP interview questions and answers for freshers
Advertisement
PHP interviews for freshers follow a pattern: a few questions on the language basics, a few on arrays and functions, some on object-oriented programming, and at least one about databases and security. Interviewers want to see that you understand why something works, not that you can recite a definition. This post gives thirty questions with short answers and code that was run on PHP 8.4. Use it to find gaps, then fix them by writing code. The free PHP course covers each topic in order.
Language basics
1. What is PHP?
PHP (a recursive acronym, "PHP: Hypertext Preprocessor") is an open-source, server-side scripting language designed for the web. The server runs your PHP file and sends the output, usually HTML, to the browser. The browser never sees the PHP code. It also runs from the command line, which is how scripts, cron jobs and tools like Composer and Laravel's artisan work.
2. How does a PHP request work?
The browser requests a URL, the web server (Apache or Nginx with PHP-FPM) passes the .php file to the PHP engine, PHP runs it (possibly querying a database), and the web server sends the generated output back. Each request starts with a fresh state; data that must survive between requests lives in a database, a session or a cookie.
3. What is the difference between echo and print?
Both output text. echo is a language construct that can take several comma-separated arguments and returns nothing; print takes one argument and returns 1. In practice, use echo.
echo "a", "b", "c"; // abc
$r = print "x"; // prints x
echo $r; // 1
4. What are PHP's data types?
Scalar types: int, float, string, bool. Compound types: array, object, callable, iterable. Special types: null, resource. PHP is dynamically typed, so a variable can change type, but you can declare types on parameters and return values, and declare(strict_types=1); makes those declarations strict.
var_dump(1, 1.5, "a", true, [1], null);
// int(1) float(1.5) string(1) "a" bool(true) array(1) {...} NULL
echo gettype(10 / 4), " ", gettype(10 / 5), " ", gettype("5" + 5); // double integer integer
5. What is the difference between == and ===?
== compares values after type juggling; === compares value and type. Prefer ===.
var_dump(0 == "a"); // false (PHP 8; was true before)
var_dump("1" == "01"); // true (both numeric strings)
var_dump("10" == "1e1"); // true
var_dump(100 == "1e2"); // true
var_dump(null == false); // true
var_dump(0 === 0.0); // false
var_dump("abc" === "abc"); // true
PHP 8 changed how numbers compare with non-numeric strings, so 0 == "a" is now false. The quirks of loose comparison are a favourite interview topic, and the lesson is simply to use ===.
6. What is the difference between isset(), empty() and is_null()?
isset($x)is true if the variable exists and is not null.empty($x)is true if the variable is unset or has a "falsy" value (0,"0","",[],null,false).is_null($x)is true only fornull, and warns on an undefined variable.
$a = 0; $b = null; $c = "";
var_dump(isset($a), empty($a)); // true, true
var_dump(isset($b), empty($b)); // false, true
var_dump(isset($c), empty($c)); // true, true
var_dump(isset($undefined)); // false (no warning)
7. What are the null coalescing and spaceship operators?
?? returns the left side if it exists and is not null, else the right side. <=> returns -1, 0 or 1 for less, equal, greater, which is handy in sort callbacks.
$name = $_GET['name'] ?? 'Guest'; // no notice if missing
echo $name, "\n"; // Guest
echo 1 <=> 2, 2 <=> 2, 3 <=> 2, "\n"; // -101
$list = [3, 1, 2];
usort($list, fn($a, $b) => $b <=> $a);
echo implode(",", $list), "\n"; // 3,2,1
8. What is the difference between include, require, include_once and require_once?
include raises a warning if the file is missing and continues; require raises a fatal error and stops. The _once versions load the file only once, which prevents "cannot redeclare function" errors. Use require for files the page cannot work without, and in modern code let Composer's autoloader load classes for you.
9. What is the difference between single and double quotes?
Double-quoted strings parse variables and escape sequences (\n); single-quoted strings do not.
$n = "Asha";
echo "Hi $n\n"; // Hi Asha (newline)
echo 'Hi $n\n', "\n"; // Hi $n\n
echo "Hi {$n}s", "\n"; // Hi Ashas (braces mark the variable name)
10. What are superglobals?
Built-in arrays available everywhere: $_GET, $_POST, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE, $_FILES, $_ENV and $GLOBALS. Treat everything in $_GET, $_POST, $_COOKIE and $_FILES as untrusted input.
Web basics
11. What is the difference between GET and POST?
GET puts data in the URL (visible, bookmarkable, length-limited, cached) and should be used only for reading data. POST puts data in the request body and is used to create or change data, and for large or sensitive form values. POST is not "secure" by itself; use HTTPS.
12. What is the difference between a session and a cookie?
A cookie is a small piece of data stored in the browser and sent with every request. A session keeps data on the server and gives the browser only a session ID in a cookie. Put the user's id and state in the session; never trust a cookie value for anything important unless it is signed or encrypted.
session_start();
$_SESSION['user_id'] = 42;
setcookie('theme', 'dark', ['expires' => time() + 86400, 'httponly' => true, 'samesite' => 'Lax']);
session_start() must run before any output is sent, otherwise PHP reports "headers already sent".
13. How do you prevent XSS?
Cross-site scripting happens when user input is printed into a page unescaped. Escape on output with htmlspecialchars:
$input = '<script>alert(1)</script>';
echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// <script>alert(1)</script>
Template engines such as Blade and Twig escape by default.
14. How do you store passwords?
Never in plain text or with MD5/SHA1. Use password_hash() and password_verify(), which add a random salt and use a slow algorithm.
$hash = password_hash("secret123", PASSWORD_DEFAULT);
var_dump(password_verify("secret123", $hash)); // true
var_dump(password_verify("wrong", $hash)); // false
echo strlen($hash) >= 60 ? "long hash\n" : "short\n"; // long hash
Store the hash in a column of at least 255 characters.
Arrays and strings
15. What types of arrays does PHP have?
PHP has one array type that works as a list and as a dictionary: indexed arrays ([1, 2]), associative arrays (['a' => 1]) and multidimensional arrays (arrays of arrays). Order is preserved.
$user = ['name' => 'Asha', 'langs' => ['PHP', 'SQL']];
echo $user['langs'][1], " ", count($user), "\n"; // SQL 2
16. Which array functions should I know?
count, array_push/[] =, array_pop, array_shift, array_merge, array_keys, array_values, in_array, array_search, array_map, array_filter, array_reduce, sort/rsort/usort, array_slice, array_unique, array_column.
$n = [1, 2, 3, 4, 5, 6];
print_r(array_filter($n, fn($x) => $x % 2 === 0)); // keeps keys 1, 3, 5
echo implode(",", array_map(fn($x) => $x * $x, $n)), "\n"; // 1,4,9,16,25,36
echo array_reduce($n, fn($c, $x) => $c + $x, 0), "\n"; // 21
var_dump(in_array("1", [1, 2, 3], true)); // false (strict)
Note that array_filter keeps the original keys; wrap it in array_values() to renumber.
17. How do you sort an associative array?
asort/arsort sort by value keeping keys; ksort/krsort sort by key; usort uses your comparison function (and reindexes).
$marks = ['Ravi' => 70, 'Asha' => 90, 'Meena' => 80];
arsort($marks);
echo implode(",", array_keys($marks)), "\n"; // Asha,Meena,Ravi
18. What are some common string functions?
strlen, strtolower/strtoupper, trim, substr, strpos (returns false if not found, so compare with !== false), str_replace, explode/implode, sprintf, ucfirst, str_contains (PHP 8). For Unicode text, use the mb_ versions.
echo strlen("café"), " ", mb_strlen("café"), "\n"; // 5 4
var_dump(strpos("hello", "h")); // int(0) -> 0 is not false!
var_dump(str_contains("hello", "ell")); // true
echo sprintf("%05.1f|%-5s|%+d", 3.14159, "ab", 7), "\n"; // 003.1|ab |+7
Functions
19. How do you pass arguments by value and by reference?
By default PHP passes by value (a copy). Prefix the parameter with & to pass a reference, so the function changes the caller's variable.
function addOne(array $a) { $a[] = 1; }
function addOneRef(array &$a) { $a[] = 1; }
$x = [];
addOne($x); echo count($x), "\n"; // 0
addOneRef($x); echo count($x), "\n"; // 1
(Objects are passed as handles, so changing an object's properties inside a function is visible outside.)
20. What are default, named and variadic arguments, and return types?
function price(float $base, float $tax = 0.18, string ...$tags): string {
return number_format($base * (1 + $tax), 2) . " [" . implode(",", $tags) . "]";
}
echo price(100), "\n"; // 118.00 []
echo price(100, tax: 0.05), "\n"; // 105.00 []
echo price(100, 0.18, "a", "b"), "\n"; // 118.00 [a,b]
Named arguments (PHP 8) let you skip optional ones.
21. What is variable scope? What do global and static do?
Variables inside a function are local. global $x imports a global (avoid it; pass parameters instead). static keeps a local variable's value between calls.
function counter() { static $n = 0; return ++$n; }
counter(); counter();
echo counter(), "\n"; // 3
22. What are anonymous functions and arrow functions?
A closure is a function without a name, and it can capture variables with use. An arrow function (fn) is a short form that captures the surrounding scope automatically, by value.
$rate = 0.1;
$a = function ($x) use ($rate) { return $x * $rate; };
$b = fn($x) => $x * $rate;
echo $a(50), " ", $b(50), "\n"; // 5 5
Object-oriented PHP
23. What are the four pillars of OOP, and how does PHP support them?
Encapsulation (visibility modifiers), inheritance (extends), polymorphism (interfaces and overriding), abstraction (abstract classes and interfaces). The concepts are explained in the Python OOP series, and the ideas carry over directly.
24. What are public, protected and private?
public is accessible from anywhere; protected from the class and its subclasses; private only from the class itself.
class Account {
public function __construct(private float $balance = 0) {} // constructor promotion (PHP 8)
public function deposit(float $n): static { $this->balance += $n; return $this; }
public function balance(): float { return $this->balance; }
}
$a = (new Account(100))->deposit(50)->deposit(25);
echo $a->balance(), "\n"; // 175
try { echo $a->balance; } catch (Error $e) { echo get_class($e), "\n"; } // Error
25. What is the difference between an abstract class, an interface and a trait?
- An abstract class can have properties, implemented methods and abstract methods; a class extends only one.
- An interface declares method signatures only; a class can implement many.
- A trait is a bundle of methods that you copy into several classes with
use, a way to reuse code without inheritance.
interface Shape { public function area(): float; }
trait Describes { public function describe(): string { return static::class . " " . number_format($this->area(), 1); } }
class Circle implements Shape {
use Describes;
public function __construct(private float $r) {}
public function area(): float { return M_PI * $this->r ** 2; }
}
echo (new Circle(2))->describe(), "\n"; // Circle 12.6
26. What are the magic methods?
Methods with names starting __ that PHP calls automatically: __construct, __destruct, __get/__set, __call, __toString, __invoke, __clone. __toString controls how an object converts to a string.
27. What is the difference between self and static, and what is a static method?
self refers to the class where the code is written; static uses late static binding and refers to the class that was actually called. A static method belongs to the class and is called with ClassName::method(), without an object.
class A { public static function make() { return new static(); } }
class B extends A {}
echo get_class(B::make()), "\n"; // B
Databases, errors and the ecosystem
28. How do you prevent SQL injection?
Never put user input into SQL text. Use prepared statements with bound parameters (PDO or mysqli). The database receives the query and the values separately, so input can never change the query's structure.
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
$pdo->exec("INSERT INTO users (name) VALUES ('Asha'), ('Ravi')");
$input = "x' OR '1'='1";
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE name = :name");
$stmt->execute([':name' => $input]);
echo $stmt->fetchColumn(), "\n"; // 0 (treated as a plain string)
echo $pdo->query("SELECT COUNT(*) FROM users WHERE name = '$input'")->fetchColumn(), "\n"; // 2 (injected!)
The second query, built by string concatenation, returned every row. This is the attack in miniature. Escaping functions are not a substitute for parameters.
29. How does PHP handle errors and exceptions?
Modern PHP throws Error and Exception objects (both implement Throwable) that you catch with try/catch/finally. Notices and warnings are reported separately; in production log them and do not display them.
function divide(int $a, int $b): float {
if ($b === 0) { throw new InvalidArgumentException("b must not be zero"); }
return $a / $b;
}
try { divide(1, 0); }
catch (InvalidArgumentException $e) { echo "caught: ", $e->getMessage(), "\n"; }
finally { echo "done\n"; }
try { intdiv(1, 0); } catch (DivisionByZeroError $e) { echo get_class($e), "\n"; }
30. What is new in PHP 8 that you should know?
match expressions, named arguments, constructor property promotion, the nullsafe operator ?->, union types, enums (8.1), readonly properties (8.1), and str_contains. Composer (the dependency manager) and PSR-4 autoloading are standard.
$status = 2;
echo match ($status) { 1 => "new", 2 => "paid", default => "unknown" }, "\n"; // paid
$user = null;
var_dump($user?->profile?->name); // NULL
enum Level: string { case Low = 'low'; case High = 'high'; }
echo Level::from('high')->name, " ", Level::tryFrom('x')?->name ?? 'none', "\n"; // High none
How to prepare
- Run every snippet above and change it until you can predict the result.
- Build a small project with a form, a database table and a login. Interviewers ask about what you built.
- Be ready to explain security: SQL injection, XSS, password hashing, CSRF, file upload validation.
- Practise explaining out loud.
- Check your knowledge with the final exam described in the PHP certificate guide, and continue with the harder PHP questions for 4+ years of experience.