Loading...

Interview Q&A – Crack Your Next Interview

1. array_merge()

The array_merge() function merges two or more arrays into one. If the arrays have the same string keys, the later value for that key will overwrite the previous one. If the keys are numeric, the values will be reindexed.
 

Example 1: Merging Indexed Arrays

$arr1 = [1, 2, 3];

$arr2 = [4, 5, 6];
$result = array_merge($arr1, $arr2);

print_r($result);

Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
 

Example 2: Merging Associative Arrays

$arr1 = ["a" => "Apple", "b" => "Banana"];

$arr2 = ["b" => "Ball", "c" => "Cat"];
$result = array_merge($arr1, $arr2);

print_r($result);

Output: Array ( [a] => Apple [b] => Ball [c] => Cat )

Note: The value of key "b" in $arr2 overwrites the value in $arr1.
 

2. array_combine()

The array_combine() function creates an associative array using one array as keys and another as values. The number of elements in both arrays must be the same.

Example:

$keys = ["name", "age", "city"];

$values = ["John", 30, "New York"];
$result = array_combine($keys, $values);

print_r($result);

Output: Array ( [name] => John [age] => 30 [city] => New York )

1. array_push(): Adds elements to the end of an array

2. array_pop(): Removes the last element of an array

3. array_keys() Retrieves all keys from an array

4. array_values(): Retrieves all values from an array

5. array_unique(): Removes duplicate values from an array

  1. echo is slightly faster than print because it does not return a value.
  2. echo can output multiple values separated by commas, while print can only take one argument.
  3. echo does not return a value, print returns 1, meaning it can be used in expressions.

  • Single quotes ('): Do not parse variables or escape sequences except \\ and \'.

  • Double quotes ("): Parse variables and escape sequences like \n, \t.

Example:

$name = "John";
echo 'Hello $name'; // Outputs: Hello $name
echo "Hello $name"; // Outputs: Hello John
 

  • == (loose comparison) checks value only.

  • === (strict comparison) checks value and type.

var_dump(5 == "5");  // true
var_dump(5 === "5"); // false

  • require stops execution on failure.

  • include issues a warning but continues execution.

  • isset() checks if a variable exists and is not null.

  • empty() checks if a variable is not set or has a falsey value (0, "", null, false).

  • explode() splits a string into an array.

  • implode() joins an array into a string.

$str = "apple,banana,grape";


$arr = explode(",", $str); // ["apple", "banana", "grape"]

$str2 = implode("-", $arr); // "apple-banana-grape

A constructor is a method that runs when an object of a class is created.

class Person {
    public $name;
    function __construct($name) {
        $this->name = $name;
    }
}
$p = new Person("John");
echo $p->name;

Use prepared statements:

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

Methods prefixed with __, like __construct(), __get(), __set(), __call()

Avoids name conflicts in large applications

Feature PHP 7 PHP 8
Performance Faster than PHP 5 Even faster with JIT compilation
JIT (Just-In-Time) Compiler ❌ No ✅ Yes (Boosts execution speed)
Union Types ❌ No ✅ Yes (`int
Named Arguments ❌ No ✅ Yes (functionName(param: value))
Match Expression ❌ No ✅ Yes (match instead of switch)
Constructor Property Promotion ❌ No ✅ Yes (Shorter constructor syntax)
Nullsafe Operator (?->) ❌ No ✅ Yes ($user?->name)
Error Handling Some fatal errors More errors converted to exceptions
Attributes (Annotations) ❌ No ✅ Yes (#[Attribute])
Deprecated Functions Some still available Removed functions like create_function()

 

  • traits are a group of functions that you include within another class. 
  • A trait is like an abstract class.
  • Traits in PHP allow you to reuse code in multiple classes without using traditional inheritance.
trait Logger {
    public function log($message) {
        echo "[LOG]: " . $message;
    }
}

class User {
    use Logger; // Importing trait
public function createUser() {
        $this->log("User Created.");
    }
}

$user = new User();
$user->createUser(); // Output: [LOG]: User Created.

Modifier Inside Class Child Class Outside Class
public ✅ Yes ✅ Yes ✅ Yes
protected ✅ Yes ✅ Yes ❌ No
private ✅ Yes ❌ No ❌ No

PHP manages memory internally through a combination of memory management layers, garbage collection, and reference counting mechanisms. Here’s a detailed breakdown of how it works:

🧠 1. Memory Allocation in PHP

PHP uses a custom memory manager that sits on top of the system's memory allocation (e.g., malloc in C).

  • Zend Memory Manager: Part of the Zend Engine (which powers PHP), it handles all PHP script memory allocations.

  • It manages small blocks (for typical variables, arrays, strings) and large blocks (for bigger structures or data).

  • The manager uses memory pools to speed up allocations and reduce system-level memory fragmentation.


📦 2. Reference Counting

PHP uses reference counting to keep track of how many variables reference a particular value in memory.

Example:

$a = "hello";
$b = $a;  // $a and $b now point to the same memory
  • A counter tracks how many variables reference the value "hello".

  • When a variable is unset or goes out of scope, the counter is decremented.

  • When the counter reaches zero, the memory is freed.


🧹 3. Garbage Collection (for Circular References)

Reference counting fails for circular references (e.g., two objects referring to each other), so PHP has a garbage collector to handle them.

  • Introduced in PHP 5.3+.

  • It runs periodically or when certain thresholds are crossed.

  • It detects and frees memory used in circular object references.


🛠️ 4. Memory Limit

  • PHP scripts have a memory limit defined by memory_limit in php.ini.

  • If a script exceeds this, PHP will throw a fatal error.

      memory_limit = 128M

📊 5. Memory Usage Functions

PHP provides built-in functions to check memory usage:

echo memory_get_usage(); // Current usage
echo memory_get_peak_usage(); // Peak usage

🔄 6. Copy-on-Write Optimization

When you assign one variable to another (especially for arrays), PHP does not copy the entire data until it is modified.

Example:

$a = [1, 2, 3];
$b = $a; // No actual data copy here
$b[] = 4; // Now a copy is made

This optimizes performance and memory.