PHP Basics & Syntax
Core PHP fundamentals every interviewer checks first: syntax, data types, variable scope, operators, includes, and OOP basics. Master these to clear the opening rounds of any PHP developer interview.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is PHP and how does it work on the server side?
Short Answer
PHP (Hypertext Preprocessor) is a widely-used, open-source, server-side scripting language primarily designed for web development. It is used to generate dynamic page content, interact with databases, manage sessions, and build robust APIs.
Detailed Explanation
Unlike client-side languages like JavaScript (which run in the user's browser), PHP code runs entirely on the web server. The server executes the PHP script, interacts with databases like MySQL if necessary, and sends plain HTML, JSON, or XML back to the browser.
Key Features of PHP:
- Server-Side: The client never sees the actual PHP code, only the rendered result.
- Database Integration: Deep, built-in support for MySQL, PostgreSQL, SQLite, and MongoDB.
- Ecosystem: Powers massive platforms like WordPress, Wikipedia, and Facebook. It also has modern, enterprise-grade frameworks like Laravel and Symfony.
- Loosely Typed: Very easy for beginners to pick up, while modern versions (PHP 7, 8) offer strict typing for enterprise reliability.
Real-World Example
When you submit a login form, the browser sends your username and password to the server. A PHP script receives that data via the $_POST array, connects to a database to verify the credentials, starts a session, and redirects you to a dashboard. None of this logic is visible to the browser.
Q2. What is the difference between echo and print in PHP?
Short Answer
Both echo and print are language constructs used to output data to the screen. The main differences are that echo can take multiple parameters and has no return value, making it marginally faster. print can only take a single argument and always returns 1, meaning it can be used in expressions.
Comparison Table
| Feature | echo |
print |
|---|---|---|
| Return Value | None (void) | Returns 1 |
| Multiple Arguments | Supported (e.g., echo "a", "b";) |
Not Supported |
| Speed | Slightly faster | Slightly slower |
| Usage in Expressions | No | Yes (e.g., $val = print("Hi");) |
Code Example
// echo multiple strings
echo "Hello ", "World", "!";
// print returning a value (useful in ternary operators)
$isPrinted = print("Hello World!"); // Outputs: Hello World!
echo $isPrinted; // Outputs: 1
// echo inside an expression will cause a Syntax Error
// $val = (echo "test"); // ERROR!
Interview Tip
In modern PHP development, always use echo. The speed difference is microscopic, but echo is the universally accepted standard in the PHP community.
Q3. What are the different data types in PHP?
Short Answer
The switch statement is a control structure used as a cleaner alternative to a long series of if...elseif...else blocks. It compares a single variable against multiple possible values (cases) and executes the corresponding block of code.
Detailed Explanation & Code Example
Each condition in a switch block is called a case. When a case matches the variable, PHP executes the code inside that case until it hits a break statement.
$role = "editor";
switch ($role) {
case "admin":
echo "You have full access.";
break;
case "editor":
echo "You can publish posts.";
break;
case "subscriber":
echo "You can read posts.";
break;
default:
// The default block runs if no cases matched
echo "Please log in.";
}
// Output: You can publish posts.
Common Mistakes: The "Fall-Through" Bug
If you forget to include the break; statement at the end of a case, PHP will execute the matched case and all subsequent cases until it hits a break or the switch ends. This is called "falling through."
// BAD CODE: Missing break statements
$number = 1;
switch ($number) {
case 1:
echo "One ";
case 2:
echo "Two ";
}
// Output: One Two
Q4. What is the difference between == and === in PHP?
Short Answer
PHP supports several types of loops to execute a block of code repeatedly: for (when you know exactly how many times you want to loop), while (when you want to loop as long as a condition is true), and foreach (specifically designed to iterate over arrays and objects).
Detailed Explanation & Examples
1. The for Loop
Used when the number of iterations is known in advance.
for ($i = 1; $i <= 3; $i++) {
echo "Iteration: $i\n";
}
// Output: Iteration 1, Iteration 2, Iteration 3
2. The while Loop
Executes a block of code as long as the specified condition is true. The condition is evaluated before the loop runs.
$count = 1;
while ($count <= 3) {
echo "Count: $count\n";
$count++;
}
3. The foreach Loop
The easiest way to iterate over arrays without needing to track an index variable.
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit\n";
}
Common Mistakes
Forgetting to increment the counter in a while loop (e.g., omitting $count++) will result in an infinite loop, crashing the script or exhausting server memory.
Q5. Explain variable scope in PHP (local, global, static).
Short Answer
break immediately exits the entire loop (or switch statement). continue skips the rest of the current loop iteration and moves directly to the next iteration.
Detailed Explanation & Examples
Example of break: Stop searching as soon as you find what you need.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break; // Exits the loop completely
}
echo $i . " ";
}
// Output: 1 2
Example of continue: Skip a specific condition but keep looping.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips printing '3', moves to '4'
}
echo $i . " ";
}
// Output: 1 2 4 5
When to use
- Use
breakwhen continuing the loop is pointless or dangerous (e.g., finding the correct user record in an array). - Use
continuewhen you want to filter out specific items in a loop but process the rest (e.g., skipping inactive users in a mailing list).
Q6. What are PHP superglobals?
Short Answer
When iterating over an associative array using a foreach loop, you use the $key => $value syntax. This allows you to access both the associative key (e.g., the string name) and its corresponding value simultaneously.
Detailed Explanation & Code Example
An associative array uses named keys that you assign to them rather than numeric indexes. A standard foreach loop can easily extract both.
$user = [
"first_name" => "Prepiq",
"role" => "Admin",
"status" => "Active"
];
// Iterating over the array, capturing both key and value
foreach ($user as $key => $value) {
// ucfirst() capitalizes the first letter of the key for display
echo ucfirst(str_replace('_', ' ', $key)) . ": " . $value . "\n";
}
Expected Output:
First name: Prepiq Role: Admin Status: Active
Q7. What is the difference between include, include_once, require, and require_once?
Short Answer
Parameters allow you to pass data into a function so that the function can process that specific data. They act as variables inside the function scope.
Detailed Explanation & Code Example
When you define a function, you can specify one or more parameters inside the parentheses. When you call the function, you pass arguments to match those parameters.
// Defining a function with two parameters: $name and $greeting
function greetUser($name, $greeting) {
echo "$greeting, $name!";
}
// Calling the function and passing arguments
greetUser("Alice", "Hello");
// Output: Hello, Alice!
greetUser("Bob", "Good morning");
// Output: Good morning, Bob!
Important Points
In modern PHP (7.0+), it is highly recommended to use Type Declarations to ensure the correct data types are passed to your parameters:
// Enforces that $age must be an integer
function setAge(int $age) {
// ...
}
Q8. What is the difference between GET and POST methods?
Short Answer
Default parameters allow you to assign a default value to a function parameter. If the caller does not pass an argument for that parameter, the default value is used instead of throwing an error.
Detailed Explanation & Code Example
Default parameters are incredibly useful for making functions flexible and keeping function signatures clean when certain arguments are almost always the same.
// $role has a default value of 'Guest'
function createUser($name, $role = "Guest") {
echo "Created user: $name, Role: $role\n";
}
// We don't provide a second argument, so 'Guest' is used.
createUser("Alice");
// Output: Created user: Alice, Role: Guest
// We provide a second argument, which overrides the default.
createUser("AdminBob", "Administrator");
// Output: Created user: AdminBob, Role: Administrator
Common Mistakes
Ordering matters! Optional parameters (those with default values) must always be placed after required parameters in the function definition. Otherwise, PHP won't know which arguments align with which parameters.
// BAD: Will cause a Fatal Error if called with only one argument
function wrongExample($role = "Guest", $name) { }
// GOOD
function correctExample($name, $role = "Guest") { }
Q9. What is type juggling / type casting in PHP?
Short Answer
By default, PHP passes variables to functions by value, meaning the function receives a copy of the variable; changing it inside the function does not affect the original. Passing by reference (using the & symbol) passes the actual memory address, so changing the variable inside the function alters the original variable.
Detailed Explanation & Code Example
1. Pass by Value (Default behavior)
function addTen($number) {
$number += 10;
}
$myAge = 25;
addTen($myAge);
echo $myAge;
// Output: 25. (The original variable is untouched)
2. Pass by Reference
Notice the & symbol before the parameter in the function signature.
function addTenByRef(&$number) {
$number += 10;
}
$myAge = 25;
addTenByRef($myAge);
echo $myAge;
// Output: 35. (The original variable was modified directly)
Interview Tip
Always note that PHP objects are passed by reference-like behavior by default. If you pass an object into a function and modify its properties, the original object outside the function will reflect those changes without needing the & symbol.
Q10. What are PHP magic constants?
Short Answer
Anonymous functions (also known as Closures) are functions that have no name. They are most commonly used as callback parameters for functions like array_map, or assigned directly to variables.
Detailed Explanation & Code Example
Unlike regular functions defined globally with the function keyword and a name, anonymous functions can be created on the fly and passed around like data.
// Assigning an anonymous function to a variable
$greet = function($name) {
return "Hello, $name";
};
echo $greet("World"); // Output: Hello, World
The use Keyword (Closures)
A massive advantage of anonymous functions in PHP is their ability to inherit variables from the parent scope using the use keyword. This makes them incredibly powerful for data filtering and manipulation.
$multiplier = 3;
$numbers = [1, 2, 3];
// Using a closure to access $multiplier from the parent scope
$multiplied = array_map(function($num) use ($multiplier) {
return $num * $multiplier;
}, $numbers);
// $multiplied is now [3, 6, 9]
Q11. What is the difference between isset(), empty(), and is_null()?
Short Answer
Recursion is a programming technique where a function calls itself repeatedly until it reaches a specific "base case" that stops the loop. It is particularly useful for tasks involving nested structures, like traversing directories, parsing XML, or calculating factorials.
Detailed Explanation & Code Example
A recursive function must always have a base case. Without a base case, the function will call itself infinitely, resulting in a "Maximum function nesting level reached" Fatal Error.
Example: Calculating Factorial (5! = 5 * 4 * 3 * 2 * 1)
function calculateFactorial($number) {
// 1. The Base Case: Stop recursion when number is 1 or less
if ($number <= 1) {
return 1;
}
// 2. The Recursive Step: Function calls itself
return $number * calculateFactorial($number - 1);
}
echo calculateFactorial(5); // Output: 120
Common Mistakes
The most common mistake with recursion is forgetting the base case, or writing a base case that is never reached due to flawed logic. This causes a stack overflow error and crashes the script.
Q12. What is the difference between indexed and associative arrays in PHP?
Short Answer
A comparison table in HTML is created using standard table tags: <table>, <thead>, <tr> (rows), <th> (headers), and <td> (data cells).
Code Example
Comparison tables typically have the features listed in the left column, and the items being compared in the subsequent columns.
<table border="1">
<thead>
<tr>
<th>Feature</th>
<th>Product A</th>
<th>Product B</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Price</strong></td>
<td>$10</td>
<td>$20</td>
</tr>
<tr>
<td><strong>Storage</strong></td>
<td>50 GB</td>
<td>Unlimited</td>
</tr>
</tbody>
</table>
Q13. What are anonymous functions and closures in PHP?
Short Answer
Generating a bar graph natively in pure PHP requires using the GD library or Imagick to draw pixels, which is tedious. The modern, best-practice approach is to generate the data in PHP, pass it to the frontend via JSON, and use a JavaScript library like Chart.js.
Detailed Example (Using Chart.js)
Here is how you bridge PHP and a frontend graphing library.
1. Prepare the Data in PHP
// Imagine this data came from a database query
$salesData = [
'January' => 150,
'February' => 200,
'March' => 180
];
// Convert to JSON so JavaScript can read it easily
$labels = json_encode(array_keys($salesData));
$values = json_encode(array_values($salesData));
2. Render the Chart in HTML/JS
<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar', // Specify bar graph
data: {
labels: <?php echo $labels; ?>,
datasets: [{
label: 'Monthly Sales',
data: <?php echo $values; ?>,
backgroundColor: 'rgba(54, 162, 235, 0.5)'
}]
}
});
</script>
PHP Basics & Syntax
Core PHP fundamentals every interviewer checks first: syntax, data types, variable scope, operators, includes, and OOP basics. Master these to clear the opening rounds of any PHP developer interview.
What is PHP and how does it work on the server side?
Short Answer PHP (Hypertext Preprocessor) is a widely-used, open-source, server-side scripting language primar...
What is the difference between echo and print in PHP?
Short Answer Both echo and print are language constructs used to output data to the screen. The main differenc...
What are the different data types in PHP?
Short Answer The switch statement is a control structure used as a cleaner alternative to a long series of if....
What is the difference between == and === in PHP?
Short Answer PHP supports several types of loops to execute a block of code repeatedly: for (when you know exa...
Explain variable scope in PHP (local, global, static).
Short Answer break immediately exits the entire loop (or switch statement). continue skips the rest of the cur...
What are PHP superglobals?
Short Answer When iterating over an associative array using a foreach loop, you use the $key => $value syntax....
What is the difference between include, include_once, require, and require_once?
Short Answer Parameters allow you to pass data into a function so that the function can process that specific...
What is the difference between GET and POST methods?
Short Answer Default parameters allow you to assign a default value to a function parameter. If the caller doe...
What is type juggling / type casting in PHP?
Short Answer By default, PHP passes variables to functions by value, meaning the function receives a copy of t...
What are PHP magic constants?
Short Answer Anonymous functions (also known as Closures) are functions that have no name. They are most commo...