Skip to Content
Course content

50: Common PHP Interview Questions on Arrays and OOP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're managing a high-end commercial kitchen. You've got your prep stations—those are your arrays. Some stations just have a list of ingredients (indexed arrays), while others have labeled containers where the label tells you exactly what's inside, like "Salt" or "Olive Oil" (associative arrays). Then you have your staff. Every chef follows a general "Chef" blueprint (a Class), but your Pastry Chef and Saucier have specific specializations (Inheritance). When you tell every chef they must be able to "clean their station" regardless of their specialty, you're essentially defining an Interface.

When you sit down for a PHP interview, the interviewer isn't just checking if you know the syntax; they're checking if you can organize your "kitchen" efficiently. I've sat on both sides of the table, and the questions usually boil down to how you handle data collections and how you structure your objects to avoid a mess of spaghetti code.

The Array Shuffle and Filter Dance

Interviewer love to ask about the difference between array_map, array_filter, and array_reduce. I usually tell my juniors to think of these as a conveyor belt. array_map changes every item on the belt; array_filter kicks some items off the belt; and array_reduce squashes everything on the belt into one single value.

// A common interview scenario: Filtering and transforming data
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'stock' => 5],
    ['name' => 'Mouse', 'price' => 25, 'stock' => 0],
    ['name' => 'Keyboard', 'price' => 75, 'stock' => 10],
];

// 1. Filter out out-of-stock items
$inStock = array_filter($products, fn($p) => $p['stock'] > 0);

// 2. Map to get only the names of in-stock items
$names = array_map(fn($p) => $p['name'], $inStock);

// 3. Reduce to find the total value of inventory
$totalValue = array_reduce($products, function($carry, $p) {
    return $carry + ($p['price'] * $p['stock']);
}, 0);

One "gotcha" I always see: array_filter preserves keys. If you filter a list and then try to loop through it with a for loop using an index, you'll hit an "Undefined offset" error. I recommend mentioning array_values() to reset those keys—it shows the interviewer you've actually written this in production, not just read a manual.

Abstracts vs. Interfaces: The Great Debate

This is the most common OOP question. If you say "they're basically the same," the interview is probably over. Here is the distinction I use: An Interface defines a capability (what it can do), while an Abstract Class defines an identity (what it is).

If I have a CanBeExported interface, both a UserReport and a ProductInvoice can implement it. They aren't the same thing, but they share the same ability. However, a BaseController abstract class provides shared logic that every UserController and PostController inherits. You use an abstract class to avoid repeating code (DRY), and an interface to ensure different classes speak the same language.

Traits and the "Composition over Inheritance" Mantra

You'll likely be asked about Traits. In PHP, we don't have multiple inheritance (a class can't extend two parents). Traits are the workaround. I think of them as "plug-ins" for your classes.

If you have a Logger trait, you can plug it into your PaymentGateway class and your UserAuth class. Neither of those classes "is a" Logger, but they both "use" logging. When an interviewer asks why you'd use a Trait over a Parent class, tell them it prevents "deep inheritance hierarchies," which are a nightmare to debug. Keep your inheritance shallow and your composition flexible.

Dependency Injection and the "New" Keyword

Finally, watch out for questions about Dependency Injection (DI). A red flag for senior devs is seeing the new keyword inside a constructor. Why? Because it hard-codes the dependency. If your OrderService creates a new MySQLDatabase() inside its constructor, you can never test that service without a real database running.

Instead, you pass the dependency in. This turns your code from a rigid brick into a Lego set. You can swap the real database for a "Mock" database during tests, and your OrderService won't even know the difference. That's the essence of decoupled code.




📋 Practical Task

Build a Decoupled Payment Processor Registry

To prove you've mastered the balance between Arrays and OOP, you're going to build a system that can handle multiple payment methods without using a single if/else or switch statement for the payment logic.

Your requirements:

  • Create a PaymentMethodInterface with a method process(float $amount): string.
  • Create two classes, StripePayment and PayPalPayment, that implement this interface. Each should return a unique string (e.g., "Processed $100 via Stripe").
  • Create a PaymentGateway class. This class should have a private array called $methods.
  • The PaymentGateway needs a method registerMethod(string $name, PaymentMethodInterface $method) to add providers to the array.
  • The PaymentGateway needs a method executePayment(string $name, float $amount) that retrieves the method from the array and calls process().

The Goal: You should be able to add a new payment method (like CryptoPayment) without ever changing the code inside the PaymentGateway class. This demonstrates the Open/Closed Principle—a favorite topic in high-level PHP interviews.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.