Basics of PHP


Basics of PHP Interview with follow-up questions

1. What is PHP and why is it used?

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed primarily for web development. PHP code executes on the web server and generates HTML that is sent to the client's browser — the client never sees the PHP source.

Key reasons PHP is used:

  • Dynamic content: PHP connects to databases and generates page content on the fly, enabling user-specific pages, content management systems, and e-commerce sites.
  • Database integration: Native support for MySQL, PostgreSQL, SQLite, and others via PDO and MySQLi makes it the foundation of popular platforms like WordPress, Drupal, and Magento.
  • Embedded in HTML: PHP can be mixed directly into HTML markup, lowering the barrier to entry for web developers.
  • Cross-platform: Runs on Linux, Windows, and macOS with Apache, Nginx, or as a standalone CLI tool.
  • Mature ecosystem: Composer package manager, frameworks like Laravel and Symfony, and a vast community mean well-tested solutions exist for almost every problem.
  • Performance: PHP 8.x with JIT compilation delivers significant speed improvements over PHP 5/7, making it competitive for high-traffic applications.

In interviews, be ready to explain the request lifecycle: browser sends HTTP request → web server (e.g., Nginx) hands off to PHP-FPM → PHP executes, queries the database, builds the response → HTML returned to browser.

↑ Back to top

Follow-up 1

What are some of the key features of PHP?

Some of the key features of PHP are:

  • Easy to learn: PHP has a simple and intuitive syntax, which makes it easy for beginners to learn and start coding.
  • Server-side scripting: PHP is primarily used for server-side scripting, allowing developers to generate dynamic web content.
  • Database integration: PHP has built-in support for various databases, making it easy to connect and interact with databases.
  • Cross-platform compatibility: PHP is compatible with multiple operating systems and web servers, allowing developers to deploy their applications on different platforms.
  • Large community and resources: PHP has a large and active community of developers, which means there are plenty of resources, libraries, and frameworks available for PHP development.
  • Open-source: PHP is open-source, which means it is free to use and developers can contribute to its development and improvement.

Follow-up 2

Can you name some popular websites that use PHP?

Some popular websites that use PHP include:

  • Facebook
  • Wikipedia
  • WordPress
  • Yahoo
  • Flickr
  • Tumblr
  • Etsy
  • Slack
  • MailChimp
  • Badoo

These are just a few examples, but PHP is widely used across the web, powering millions of websites and web applications.

Follow-up 3

What are the advantages of using PHP over other languages?

Some advantages of using PHP over other languages are:

  • Easy to learn: PHP has a simple and intuitive syntax, making it easier for beginners to learn compared to other languages.
  • Large community and resources: PHP has a large and active community of developers, which means there are plenty of resources, libraries, and frameworks available for PHP development.
  • Database integration: PHP has built-in support for various databases, making it easy to connect and interact with databases.
  • Cross-platform compatibility: PHP is compatible with multiple operating systems and web servers, allowing developers to deploy their applications on different platforms.
  • Performance: PHP is known for its fast execution speed, making it suitable for high-traffic websites and applications.
  • Open-source: PHP is open-source, which means it is free to use and developers can contribute to its development and improvement.

However, it's important to note that the choice of programming language depends on the specific requirements of the project and the preferences of the development team.

2. What is the syntax of PHP?

PHP code is embedded within HTML using opening and closing tags. The standard tag is `. A short-echo tag= ... ?>` is also available for outputting a single expression.


Key syntax rules:

  • Every statement ends with a semicolon (;).
  • Variables start with a dollar sign: $name = "Alice";
  • Comments use // or # for single-line, and /* ... */ for multi-line.
  • PHP is loosely typed by default, but strict types can be enforced per-file with declare(strict_types=1); — a practice strongly encouraged in modern PHP.
  • String concatenation uses the dot operator: "Hello" . " World".
  • PHP is case-insensitive for function and class names, but case-sensitive for variable names.

Modern PHP (8.x) encourages typed properties, union types, and named arguments, which add stricter structure to the language while keeping its flexibility.

↑ Back to top

Follow-up 1

How do you declare variables in PHP?

In PHP, variables are declared using the $ symbol followed by the variable name. For example, $name = 'John';

Follow-up 2

How do you write comments in PHP?

In PHP, single-line comments start with // or #, and multi-line comments are enclosed within /* */. For example:

// This is a single-line comment

/* This is a multi-line comment */

Follow-up 3

What are the rules for naming variables in PHP?

In PHP, variable names must start with a letter or underscore, followed by any combination of letters, numbers, or underscores. Variable names are case-sensitive. For example, $myVariable, $_myVariable, $my_variable are all valid variable names.

3. What are the data types supported by PHP?

PHP supports the following data types, grouped into three categories:

Scalar types

  • int — whole numbers (e.g., 42, -7)
  • float — decimal numbers (e.g., 3.14)
  • string — sequence of characters (e.g., "hello")
  • booltrue or false

Compound types

  • array — ordered map; can hold mixed values and be indexed or associative
  • object — instance of a class
  • callable — anything that can be called as a function (closures, method references, etc.)
  • iterable — accepts any array or object implementing Traversable

Special types

  • null — represents no value
  • resource — a reference to an external resource such as a file handle or database connection (legacy; modern APIs avoid raw resources)

PHP 8.x additions worth knowing in interviews:

  • Union types (int|string) — a parameter or return value that accepts multiple types
  • Intersection types (Iterator&Countable) — PHP 8.1+, value must satisfy all listed interfaces
  • never return type — PHP 8.1+, indicates a function always throws or calls exit()
  • enum — PHP 8.1+, a first-class enumeration type (backed by int or string, or pure)

PHP is dynamically typed, so a variable's type can change at runtime. Use gettype() or get_debug_type() (PHP 8.0+) to inspect types, and cast with (int), (string), etc.

↑ Back to top

Follow-up 1

How does PHP handle type juggling?

PHP is a loosely typed language, which means that it automatically converts variables from one data type to another as needed. This is known as type juggling. For example, if you concatenate a string and an integer, PHP will automatically convert the integer to a string before performing the concatenation. Similarly, if you perform a mathematical operation on a string that contains a numeric value, PHP will automatically convert the string to a number before performing the operation. However, type juggling can sometimes lead to unexpected results, so it's important to be aware of how PHP handles different data types.

Follow-up 2

What is the difference between an integer and a float in PHP?

In PHP, an integer is a whole number without a decimal point, while a float is a number with a decimal point. Integers can be positive or negative, while floats can also have fractional parts. For example, 5 is an integer, while 3.14 is a float. When performing mathematical operations, PHP will automatically convert integers to floats if necessary. It's important to note that floats have limited precision, so they may not always be accurate for precise calculations.

Follow-up 3

What is the difference between a string and an array in PHP?

In PHP, a string is a sequence of characters, while an array is an ordered collection of values. Strings are used to store and manipulate text, while arrays are used to store and access multiple values. Strings can be accessed character by character, while arrays can be accessed element by element. Additionally, strings have various built-in functions for manipulating text, such as concatenation, substring extraction, and case conversion. Arrays have their own set of functions for manipulating and iterating over the values they contain.

4. How do you include one PHP file into another?

PHP provides four statements for including external files, with important behavioral differences:

Statement File missing behavior Included multiple times?
include Warning, script continues Yes
require Fatal error, script halts Yes
include_once Warning, script continues No (skipped on repeat)
require_once Fatal error, script halts No (skipped on repeat)
require 'config.php';        // halt if missing — use for critical dependencies
include 'optional_widget.php'; // warn if missing, continue — use for optional content
require_once 'Database.php';  // most common in class-based code to avoid redeclaration errors

Interview gotchas:

  • require_once and include_once track the resolved file path, so including the same file via two different relative paths may not be caught as a duplicate. Autoloading with Composer (spl_autoload_register) is the modern best practice — manually writing require_once for every class is considered a code smell in projects using PSR-4.
  • The included file inherits the variable scope of the point where the statement appears. Variables defined inside a function are not automatically available in the included file unless passed explicitly.
↑ Back to top

Follow-up 1

What is the difference between include and require in PHP?

The main difference between include and require in PHP is how they handle errors when the file to be included is not found.

  • include statement will only produce a warning (non-fatal error) and continue executing the script if the file is not found. This means that the script will still run, but the included file will be skipped.

  • require statement, on the other hand, will produce a fatal error and stop the script execution if the file is not found. This means that the script will terminate and an error message will be displayed.

In general, it is recommended to use require when including files that are essential for the script to run, and use include for files that are not critical and can be skipped if not found.

Follow-up 2

What happens if the file to be included is not found in both cases?

If the file to be included is not found, the behavior differs depending on whether you use include or require statement:

  • If you use include statement and the file is not found, a warning (non-fatal error) will be generated, and the script will continue executing. The included file will be skipped, and the script will proceed to the next statement.

  • If you use require statement and the file is not found, a fatal error will be generated, and the script execution will be stopped. An error message will be displayed, and the script will terminate.

It is important to handle these errors properly to ensure the smooth execution of your PHP scripts. You can use error handling techniques such as try-catch blocks or the error_reporting function to handle and display errors in a controlled manner.

Follow-up 3

How can you prevent a PHP file from being included more than once?

To prevent a PHP file from being included more than once, you can use the include_once or require_once statement instead of include or require.

The include_once statement checks if the file has already been included, and if so, it will not include it again. This prevents duplicate inclusion of the same file.

Similarly, the require_once statement works in the same way, but it will produce a fatal error if the file cannot be included.

Here is an example of using include_once:

include_once 'filename.php';

Using include_once or require_once is a good practice to avoid conflicts and errors that may occur when including the same file multiple times.

5. What is the use of 'echo' in PHP?

echo outputs one or more strings to the browser or standard output. It is a language construct, not a function, so parentheses are optional.

HTML is fine here too";
?>

The short-echo tag is a convenient alternative for templates:

<p>Welcome, = htmlspecialchars($username) ?&gt;</p>

echo vs print: Both output a string, but print always returns 1 and only accepts a single argument. echo is marginally faster and is preferred in practice.

Interview note: Always escape output to prevent XSS. Use htmlspecialchars() when echoing user-supplied data into HTML context, or a template engine like Blade (Laravel) or Twig (Symfony) which auto-escapes by default.

↑ Back to top

Follow-up 1

What is the difference between 'echo' and 'print' in PHP?

In PHP, both 'echo' and 'print' are used to output text or variables. However, there are a few differences between them:

  1. Syntax: 'echo' does not require parentheses, while 'print' requires parentheses.

  2. Return Value: 'echo' does not have a return value, while 'print' returns 1.

  3. Speed: 'echo' is generally faster than 'print'.

Here is an example of using 'print' to output a string:


Follow-up 2

Can 'echo' and 'print' be used interchangeably?

Yes, 'echo' and 'print' can be used interchangeably in most cases. However, there are some subtle differences between them, as mentioned earlier. It is generally recommended to use 'echo' for better performance, unless you specifically need the return value of 'print'.

Follow-up 3

How do you output HTML or other types of content using 'echo'?

To output HTML or other types of content using 'echo', you can simply include the HTML or content within the 'echo' statement. Here is an example of using 'echo' to output an HTML paragraph:

This is an example paragraph.';
?&gt;

You can also concatenate variables or use string interpolation to include dynamic content within the HTML or content being echoed.

Live mock interview

Mock interview: Basics of PHP

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.