PHP Basics Interview Questions

🧾 PHP Basics – Interview Questions


🔹 1. Basic Questions (Very Important)

1️⃣ What is PHP?
👉 PHP (Hypertext Preprocessor) is a server-side scripting language used to build dynamic websites.


2️⃣ What are variables in PHP?
👉 Variables store data and start with $
Example:

$name = "Aditya";

3️⃣ Is PHP case-sensitive?
👉 Variables are case-sensitive ($name$Name)
👉 Keywords are NOT case-sensitive (echo = ECHO)


4️⃣ What are data types in PHP?
👉 Common types:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object

5️⃣ Difference between echo and print?

echoprint
FasterSlower
No return valueReturns 1
Can print multiple valuesOnly one

🔹 2. Intermediate Questions

6️⃣ What is a constant in PHP?
👉 A constant is a fixed value that cannot be changed.

define("SITE", "SOA Technology");

7️⃣ What is the difference between == and ===?

  • == → compares value
  • === → compares value + data type
10 == "10"   // true
10 === "10" // false

8️⃣ What are operators in PHP?
👉 Symbols used to perform operations.

Types:

  • Arithmetic (+ - * / %)
  • Comparison (== != > <)
  • Logical (&& || !)

9️⃣ What is the use of var_dump()?
👉 It shows data type + value

var_dump(10); // int(10)

🔟 What are comments in PHP?
👉 Used to explain code

// single line
# single line/*
multi-line
*/

🔹 3. Tricky Questions (Asked in Interviews)

1️⃣1️⃣ What will be the output?

$x = 5;
echo $x++;

👉 Output: 5 (post-increment)


1️⃣2️⃣ What will be the output?

$x = 5;
echo ++$x;

👉 Output: 6 (pre-increment)


1️⃣3️⃣ Difference between single quotes and double quotes?

  • ' ' → No variable parsing
  • " " → Variables are parsed
$name = "Aditya";echo 'Hello $name'; // Hello $name
echo "Hello $name"; // Hello Aditya

1️⃣4️⃣ Can we redeclare a constant?
👉 ❌ No


1️⃣5️⃣ What happens if you use an undefined variable?
👉 PHP shows a warning/notice


🔹 4. Practical / Coding Questions

1️⃣6️⃣ Write a program to check even or odd

$num = 4;
if($num % 2 == 0){
echo "Even";
} else {
echo "Odd";
}

1️⃣7️⃣ Swap two numbers

$a = 5;
$b = 10;$a = $a + $b;
$b = $a - $b;
$a = $a - $b;

1️⃣8️⃣ Find largest of two numbers

$a = 10;
$b = 20;echo ($a > $b) ? $a : $b;

🔥 Pro Interview Tips

  • Always explain why, not just code
  • Be clear on == vs === (very important)
  • Know basic syntax + output prediction
  • Practice small programs

practice questions on PHP Basics

🧾 PHP Basics – Practice Questions


🔹 Level 1: Beginner

1️⃣ Create variables for:

  • Your name
  • Your age
  • Your city
    Then print them using echo.

2️⃣ Create two numbers and:

  • Add them
  • Subtract them
  • Multiply them

3️⃣ Write a PHP script to:

  • Store a string "Welcome to PHP"
  • Print it using both echo and print

4️⃣ Create a constant named SITE_URL and assign your website URL. Then print it.


5️⃣ Identify the data type of these variables using var_dump():

$a = 100;
$b = "Hello";
$c = 10.5;
$d = true;

🔹 Level 2: Intermediate

6️⃣ Compare two variables:

$a = 10;
$b = "10";
  • Check using == and ===
  • Explain the output

7️⃣ Write a program to check:

  • If a number is greater than 50 or not (use comparison + echo result)

8️⃣ Use logical operators:

  • Create two variables $x = true, $y = false
  • Test AND, OR, NOT

9️⃣ Create a calculator using variables:

  • Perform all arithmetic operations (+, -, *, /, %)

🔟 Write a PHP script with:

  • Single-line comment
  • Multi-line comment
    Explain what your code does

🔹 Level 3: Challenge

1️⃣1️⃣ Create 3 variables:

  • Name (string)
  • Marks (integer)
  • Pass status (boolean)

Print all values with proper labels.


1️⃣2️⃣ Swap two variables without using a third variable

$a = 5;
$b = 10;

1️⃣3️⃣ Check if a number is even or odd using %


1️⃣4️⃣ Create a simple bill:

  • Product price = 100
  • GST = 18%
  • Calculate total price

1️⃣5️⃣ Write a script that:

  • Uses all operators (arithmetic + comparison + logical) in one example

🚀 Bonus (Important for Interviews)

👉 What will be the output?

$x = 5;
echo $x++;
echo ++$x;

💡 Tip

Try to run these on your server (XAMPP / localhost)

2. PHP Basics

🔹 1. Variables & Data Types

✅ Variables

Variables are used to store data.

👉 In PHP, variables start with $

$name = "Aditya";
$age = 25;

✅ Rules:

  • Must start with $
  • Cannot start with a number
  • Case-sensitive ($name$Name)

✅ Data Types in PHP

TypeExampleDescription
String"Hello"Text
Integer10Whole numbers
Float10.5Decimal numbers
Booleantrue/falseTrue or false
Array["a", "b"]Multiple values
Objectnew ClassName()Complex data
$name = "Aditya";   // String
$age = 25; // Integer
$price = 99.99; // Float
$isActive = true; // Boolean

🔹 2. Constants

Constants are values that cannot be changed once defined.

define("SITE_NAME", "SOA Technology");
echo SITE_NAME;

✅ Rules:

  • No $ symbol
  • Always global
  • Value cannot be modified

🔹 3. Operators

Operators are used to perform operations on variables


➤ Arithmetic Operators

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
$a = 10;
$b = 5;
echo $a + $b; // 15

➤ Comparison Operators

OperatorMeaning
==Equal
===Equal (value + type)
!=Not equal
>Greater
<Less
$a = 10;
$b = "10";var_dump($a == $b); // true
var_dump($a === $b); // false

➤ Logical Operators

OperatorMeaning
&&AND
`
!NOT
$x = true;
$y = false;var_dump($x && $y); // false

🔹 4. Echo vs Print

Both are used to display output


✅ echo

  • Faster
  • Can print multiple values
echo "Hello ", "World";

✅ print

  • Slower than echo
  • Returns value (1)
print "Hello World";

🔥 Key Difference

Featureechoprint
SpeedFasterSlower
Multiple argumentsYesNo
Return valueNoYes (1)

🔹 5. Comments

Comments are used to explain code (ignored by PHP)


➤ Single-line comment

// This is a comment
# This is also a comment

➤ Multi-line comment

/*
This is a
multi-line comment
*/

✅ Summary

  • Variables store data ($name)
  • Data types define the kind of data
  • Constants are fixed values
  • Operators perform operations
  • echo & print show output
  • Comments explain code

PHP Practice Questions (Beginner Level)

🔹 1. Theory Questions

  1. What is PHP? Why is it called a server-side language?
  2. Who created PHP and in which year?
  3. What is the difference between client-side and server-side scripting?
  4. Name any 3 uses of PHP.
  5. What is XAMPP? Why do we use it?
  6. What is the role of Apache in XAMPP?
  7. Where should PHP files be stored in XAMPP?
  8. What is the latest version of PHP?
  9. Can the browser read PHP code directly? Why?
  10. What is the full form of PHP?

🔹 2. Output-Based Questions

👉 Predict the output:

Q1

<?php
echo "Hello PHP";
?>

Q2

<?php
$name = "Aditya";
echo $name;
?>

Q3

<?php
$a = 10;
$b = 20;
echo $a + $b;
?>

Q4

<?php
echo "10" + 5;
?>

Q5

<?php
echo "Hello" . " World";
?>

🔹 3. Error Finding Questions

👉 Find and fix errors:

Q1

<?php
echo Hello World;
?>

Q2

<?php
$name = Aditya;
echo $name;
?>

Q3

<?php
echo "Welcome"
?>

Q4

<?php
$1name = "PHP";
echo $1name;
?>

🔹 4. Practical Coding Questions

👉 Write programs:

Q1

Print your name using PHP


Q2

Create variables for:

  • Name
  • Age
    Print:
    👉 My name is ___ and I am ___ years old

Q3

Add two numbers and print result


Q4

Print this output:

Welcome to PHP Programming

Q5

Create a PHP file and run it on localhost


🔹 5. Challenge Questions 🚀

Q1

Print:

Hello
World

(Use single echo)


Q2

Create variables:

$a = 5;
$b = 3;

Print:

Sum = 8

Q3

Mix HTML + PHP:

<h1>Welcome Message</h1>

Use PHP to print your name below it


🎯 Bonus Teaching Tip

👉 Ask students to:

  • Install XAMPP
  • Create 3 PHP files
  • Run them in browser

1. Introduction to PHP

✅ 1. What is PHP?

PHP stands for Hypertext Preprocessor.

  • It is a server-side scripting language
  • Used to create dynamic websites
  • Runs on the server, not in the browser

👉 Example:

<?php
echo "Hello World";
?>

👉 Output in browser:

Hello World

📌 Key Uses:

  • Login systems
  • Contact forms
  • E-commerce websites
  • CMS (WordPress, Joomla)

✅ 2. History & Versions

  • Created by Rasmus Lerdorf (1994)
  • Initially called Personal Home Page
  • Later evolved into a full programming language

📌 Important Versions:

  • PHP 5 → OOP introduced
  • PHP 7 → Faster performance 🚀
  • PHP 8 → Latest features (JIT, better error handling)

👉 Current modern version: PHP 8+


✅ 3. How PHP Works (Client vs Server)

📌 Flow:

  1. User opens website in browser (Client)
  2. Request goes to server
  3. Server runs PHP code
  4. Server sends HTML output
  5. Browser displays result

👉 Diagram (simple):

Browser → Server (PHP runs) → HTML → Browser

📌 Important:

  • Browser never sees PHP code
  • It only sees the output (HTML)

✅ 4. Installing XAMPP / WAMP / LAMP

To run PHP locally, you need a local server.

🔹 Options:

  • XAMPP (Windows, Linux, Mac) ⭐ Recommended
  • WAMP (Windows)
  • LAMP (Linux)

🔹 XAMPP Installation Steps:

  1. Download from: https://www.apachefriends.org
  2. Install software
  3. Open XAMPP Control Panel
  4. Start:
    • Apache ✅
    • MySQL ✅

📁 Folder:

htdocs/

👉 Place your PHP files here


✅ 5. Running First PHP Script

Step 1: Create file

hello.php

Step 2: Write code

<?php
echo "My First PHP Program!";
?>

Step 3: Save in:

htdocs/hello.php

Step 4: Run in browser:

http://localhost/hello.php

👉 Output:

My First PHP Program!

✅ 6. PHP Syntax Basics

🔹 PHP Tags

<?php
// PHP code here
?>

🔹 Echo (Print Output)

echo "Hello";
print "World";

🔹 Variables

$name = "Aditya";
$age = 25;

📌 Rules:

  • Starts with $
  • Case-sensitive

🔹 Comments

// Single line
# Single line
/* Multi-line */

🔹 Data Types

$string = "Hello";
$int = 10;
$float = 10.5;
$bool = true;
$array = [1,2,3];

🔹 Simple Example

<?php
$name = "Aditya";
echo "Welcome " . $name;
?>

👉 Output:

Welcome Aditya

🎯 Summary

  • PHP is a server-side language
  • Used to build dynamic websites
  • Runs on Apache server (XAMPP)
  • Easy syntax for beginners

complete PHP syllabus (beginner → advanced → professional level)

🧠 PHP Complete Syllabus (2026 Updated)

🔰 1. Introduction to PHP

  • What is PHP?
  • History & Versions
  • How PHP works (Client vs Server)
  • Installing XAMPP / WAMP / LAMP
  • Running first PHP script
  • PHP syntax basics

🧾 2. PHP Basics

  • Variables & Data Types
  • Constants
  • Operators (Arithmetic, Comparison, Logical)
  • Echo vs Print
  • Comments

🔀 3. Control Structures

  • If, Else, Elseif
  • Switch Case
  • Ternary Operator
  • Match Expression (PHP 8+)

🔁 4. Loops

  • for loop
  • while loop
  • do-while loop
  • foreach loop
  • Break & Continue

📦 5. Functions

  • User-defined functions
  • Function parameters
  • Default arguments
  • Return values
  • Variable functions
  • Recursive functions

📚 6. Arrays

  • Indexed arrays
  • Associative arrays
  • Multidimensional arrays
  • Array functions (sort, merge, filter, map)

🔤 7. Strings

  • String functions
  • String manipulation
  • Explode / Implode
  • Regular Expressions (Regex)

📂 8. Forms Handling

  • GET vs POST
  • Form validation
  • Sanitization
  • File upload handling

🍪 9. Cookies & Sessions

  • Creating cookies
  • Deleting cookies
  • Sessions (start, destroy)
  • Session security

🗄️ 10. File Handling

  • Read/write files
  • fopen, fread, fwrite
  • File upload system
  • Directory handling

🧱 11. Object-Oriented PHP (OOP)

  • Classes & Objects
  • Properties & Methods
  • Constructor & Destructor
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Traits
  • Interfaces & Abstract Classes

🔌 12. Database (MySQL)

  • Introduction to MySQL
  • Connecting PHP with MySQL
  • MySQLi & PDO
  • CRUD operations (Create, Read, Update, Delete)
  • Prepared Statements (important 🔥)

🔐 13. Security in PHP

  • SQL Injection prevention
  • XSS protection
  • CSRF protection
  • Password hashing (password_hash)
  • Data sanitization

🌐 14. Working with APIs

  • REST API basics
  • Fetch API using PHP (cURL)
  • JSON handling (encode/decode)

⚙️ 15. Error Handling

  • Error types
  • try-catch blocks
  • Custom errors
  • Debugging

📦 16. Composer & Packages

  • What is Composer?
  • Installing libraries
  • Autoloading

🧩 17. MVC Architecture

  • What is MVC?
  • Folder structure
  • Basic MVC project

🚀 18. PHP Frameworks (Overview + Practice)

  • Laravel (Most Important 🔥)
  • CodeIgniter
  • Symfony (advanced)

🛠️ 19. Advanced Topics

  • RESTful API Development
  • Authentication (JWT, Sessions)
  • Middleware
  • Dependency Injection

📊 20. Performance Optimization

  • Caching
  • OPcache
  • Code optimization

🌍 21. Deployment

  • Hosting (Shared / VPS)
  • Domain setup
  • cPanel basics
  • Git deployment

💼 Final Projects (Very Important 🚀)

Build these for portfolio:

  1. Blog CMS (like WordPress basic)
  2. Login/Register system
  3. E-commerce website
  4. REST API (CRUD)
  5. File upload system
  6. Admin dashboard
  7. URL shortener
  8. Chat system (AJAX + PHP)

📅 Suggested Learning Plan

  • Week 1–2 → Basics + Control
  • Week 3 → Functions + Arrays
  • Week 4 → Forms + Sessions
  • Week 5 → MySQL + CRUD
  • Week 6 → OOP + Security
  • Week 7 → API + Advanced
  • Week 8 → Final Projects

🔥 Pro Tips (Important)

  • Practice daily (coding > theory)
  • Build projects early
  • Focus on security + database
  • Learn Laravel after core PHP

zobo.php-intellisense for xampp

To use the zobo.php-intellisense extension with XAMPP, you must first install the extension in Visual Studio Code and then ensure VS Code can find the PHP executable provided by XAMPP. 

Step 1: Install the Extension in VS Code

  1. Open Visual Studio Code.
  2. Go to the Extensions view by clicking the Extensions icon in the Activity Bar or by pressing Ctrl+Shift+X.
  3. In the search bar, type zobo.php-intellisense.
  4. Click Install next to the extension in the search results. 

Step 2: Configure the PHP Executable Path 

The extension needs to know where your PHP installation (which comes with XAMPP) is located to provide code intelligence and run the language server. 

  1. Find the path to your php.exe file. In a standard XAMPP installation on Windows, it is usually C:\xampp\php\php.exe.
  2. In VS Code, open the Command Palette by pressing Ctrl+Shift+P.
  3. Type “Open Settings” and select Preferences: Open User Settings or Preferences: Open Workspace Settings if configuring for a specific project.
  4. In the Settings tab, search for php.executablePath.
  5. Enter the full path to your php.exe file in the field provided, for example: C:\\xampp\\php\\php.exe. Note the double backslashes which are often required in JSON settings.
  6. Relaunch VS Code for the changes to take effect. 

Step 3: Disable Built-in PHP Language Features 

To avoid conflicts, it is recommended to disable VS Code’s default PHP language features, which the zobo extension replaces. 

  1. Go back to the Extensions view (Ctrl+Shift+X).
  2. Search for @builtin php.
  3. Find the extension named PHP Language Features and click the Disable button for it.
  4. Ensure PHP Language Basics remains enabled for basic syntax highlighting.

get domain from url in php

To get the domain from a URL in PHP, the built-in parse_url() function is the recommended method. 

Using parse_url() (Recommended) 

The parse_url() function can extract various components of a URL string, including the host. 

php

<?php
$url = "https://www.example.com/path/to/page.html?query=value";

// Get only the 'host' component from the URL
$host = parse_url($url, PHP_URL_HOST);

echo $host;
// Output: www.example.com
?>

Note: If the input URL is missing the scheme (http:// or https://), parse_url() might not work as expected. You can add a default scheme if one is not present in the original string. 

Getting the Root Domain (without ‘www’ or subdomains)

If you need only the root domain (e.g., example.com from www.example.com or sub.example.com), you can use string manipulation with str_replace() and explode()

php

<?php
$url = "https://sub.example.com";

// 1. Get the host name
$host = parse_url($url, PHP_URL_HOST);

// 2. Remove 'www.' if it exists
$host = str_replace('www.', '', $host);

// This simple method works for most common domains but may fail with complex TLDs like co.uk.
echo $host;
// Output: example.com
?>

For robust handling of complex top-level domains (like .co.uk.gouv.fr), string manipulation can be unreliable. A professional solution would use a library that incorporates the Public Suffix List, such as the PHP Domain Parser library.

get substring from string in php from first matching

To extract a substring in PHP based on the first occurrence of another matching substring or character, you can use a combination of the built-in functions strpos() and substr(), or the specialized function strstr()

Here are the most common methods:

Method 1: Using strpos() and substr()

This method is highly flexible and works across all PHP versions. strpos() finds the position of the first match, and substr() extracts the desired portion. 

To get the part after the first match:

php

$data = "123_String_with_more_underscores";
$delimiter = "_";

// Find the position of the first occurrence of the delimiter
$pos = strpos($data, $delimiter);

// Check if the delimiter was found (use !== false because position 0 is a valid match)
if ($pos !== false) {
    // Extract the substring starting from the character after the delimiter
    $whatIWant = substr($data, $pos + 1);
    echo $whatIWant; // Output: String_with_more_underscores
} else {
    echo "Delimiter not found.";
}

To get the part before the first match:

php

$data = "johnclark@mail.com";
$delimiter = "@";

// Find the position of the first occurrence
$pos = strpos($data, $delimiter);

if ($pos !== false) {
    // Extract the substring from the beginning (index 0) up to the position of the delimiter
    $whatIWant = substr($data, 0, $pos);
    echo $whatIWant; // Output: johnclark
} else {
    echo "Delimiter not found.";
}

Method 2: Using strstr()

The strstr() function (case-sensitive) returns the entire portion of the string starting from the first occurrence of the specified match. 

  • To get the part from the first match to the end:php$str = "Welcome to GeeksforGeeks"; $match = "Geeks"; $result = strstr($str, $match); echo $result; // Output: GeeksforGeeks
  • For PHP 5.3.0+ (to get the part before the first match), you can pass a third optional parameter true:php$str = "johnclark@mail.com"; $result = strstr($str, "@", true); // The 'true' parameter returns the part *before* the match echo $result; // Output: johnclark  

For a case-insensitive search, use stristr() instead. 

Method 3: Using explode()

If your delimiter is a simple string and you need the portion after it, explode() can split the string into an array. By setting a limit of 2, you only create two elements. 

php

$string = '233718_This_is_a_string';
$delimiter = '_';

// Split the string into a max of 2 elements
$parts = explode($delimiter, $string, 2);

// The second element ([1]) is the part after the first delimiter
if (isset($parts[1])) {
    echo $parts[1]; // Output: This_is_a_string
}

truncate character in php if exceed length

To truncate a string in PHP if its length exceeds a specified limit, the substr() function is commonly used.

Here is an example of how to truncate a string and append an ellipsis if it exceeds a certain length:

<?php

function truncateString(string $text, int $maxLength, string $ellipsis = '...'): string
{
    if (strlen($text) > $maxLength) {
        return substr($text, 0, $maxLength) . $ellipsis;
    }
    return $text;
}

$longString = "This is a very long string that needs to be truncated if it exceeds a certain length.";
$shortString = "Short text.";

echo "Truncated long string: " . truncateString($longString, 20) . "\n";
echo "Short string (not truncated): " . truncateString($shortString, 20) . "\n";

?>

In this example:

  • truncateString function: This function takes three arguments:
    • $text: The original string to be truncated.
    • $maxLength: The maximum desired length of the string before truncation.
    • $ellipsis: (Optional) The characters to append to the truncated string (defaults to ...).
  • strlen($text): This function calculates the length of the string.
  • Conditional Check: The if statement checks if the length of $text is greater than $maxLength.
  • substr($text, 0, $maxLength): If the string is too long, substr() extracts a portion of the string starting from the beginning (offset 0) up to the specified $maxLength.
  • Concatenation: The extracted substring is then concatenated with the $ellipsis to indicate truncation.
  • Return Original String: If the string is not longer than $maxLength, the original string is returned unchanged.