πŸ”’ Array Basics

Index: Basics Index | Parent: Array Index


1. What is an Array?

An array is a data structure that stores multiple values in a single variable, in contiguous memory (in low-level languages). In PHP, arrays are dynamic and can grow.

Memory Model (conceptual):
Index:  [0]   [1]   [2]   [3]   [4]
Value:  [10]  [20]  [30]  [40]  [50]
Addr:   1000  1004  1008  1012  1016

Key Properties:


2. PHP Array Types

2a. Indexed Array (most common in DSA)

$arr = [10, 20, 30, 40, 50];
echo $arr[0]; // 10
echo $arr[2]; // 30

2b. Associative Array (key-value β†’ like a HashMap)

$user = [
    'name'  => 'Alice',
    'age'   => 25,
    'email' => 'alice@example.com'
];
echo $user['name']; // Alice

πŸ’‘ Laravel uses this everywhere: $request->all(), model attributes, config values

2c. Multidimensional Array (matrix / 2D array)

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
echo $matrix[1][2]; // 6 (row 1, col 2)

3. CRUD Operations

CREATE

// Method 1: Direct declaration
$arr = [1, 2, 3, 4, 5];

// Method 2: Push to end β†’ O(1)
$arr[] = 6;
array_push($arr, 7, 8);

// Method 3: Insert at specific index β†’ O(n)
array_splice($arr, 2, 0, [99]); // insert 99 at index 2

READ

$arr = [10, 20, 30, 40, 50];

// By index β†’ O(1)
echo $arr[0];          // 10

// First element
echo reset($arr);      // 10
echo $arr[0];          // 10

// Last element
echo end($arr);        // 50
echo $arr[count($arr) - 1]; // 50

// Length
echo count($arr);      // 5

UPDATE

$arr = [10, 20, 30];
$arr[1] = 99;          // Update index 1 β†’ O(1)
// Result: [10, 99, 30]

DELETE

$arr = [10, 20, 30, 40, 50];

// Remove last β†’ O(1)
array_pop($arr);       // removes 50

// Remove first β†’ O(n) (shifts all)
array_shift($arr);     // removes 10

// Remove by index β†’ O(n)
unset($arr[2]);        // removes element at index 2
$arr = array_values($arr); // re-index after unset

// Remove by value
$arr = array_diff($arr, [30]); // removes all 30s

4. Traversal Patterns

Pattern 1: Simple for loop (when you need index)

$arr = [10, 20, 30, 40, 50];
for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i] . "\n";
}

Use when: You need index, or comparing $arr[$i] with $arr[$i+1]

Pattern 2: foreach (cleanest for PHP)

foreach ($arr as $value) {
    echo $value . "\n";
}

// With index
foreach ($arr as $index => $value) {
    echo "$index: $value\n";
}

Use when: Just need values, associative arrays, Laravel collections

Pattern 3: while loop (custom stepping)

$i = 0;
while ($i < count($arr)) {
    echo $arr[$i];
    $i += 2; // skip every other element
}

Use when: Two pointers, custom stepping, break conditions

Pattern 4: Reverse traversal

for ($i = count($arr) - 1; $i >= 0; $i--) {
    echo $arr[$i] . "\n";
}

Use when: Reversing, working backwards

Pattern 5: Nested loop (2D array / matrix)

$matrix = [[1,2,3],[4,5,6],[7,8,9]];
for ($i = 0; $i < count($matrix); $i++) {
    for ($j = 0; $j < count($matrix[$i]); $j++) {
        echo $matrix[$i][$j] . " ";
    }
    echo "\n";
}

Use when: Matrix problems, pair comparison O(nΒ²)


5. Common Mistakes to Avoid

❌ Off-by-one Error

// WRONG: goes out of bounds
for ($i = 0; $i <= count($arr); $i++) { // <= causes error
    echo $arr[$i];
}

// CORRECT
for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i];
}

❌ Forgetting array_values() after unset

$arr = [10, 20, 30, 40];
unset($arr[1]);
// $arr is now [0=>10, 2=>30, 3=>40] β€” index 1 is MISSING!

$arr = array_values($arr);
// Now: [0=>10, 1=>30, 2=>40] β€” re-indexed correctly

❌ Reference bug in foreach

$arr = [1, 2, 3, 4, 5];
foreach ($arr as &$val) {
    $val *= 2;
}
// ⚠️ $val is still a reference to last element!
unset($val); // Always unset after reference foreach

❌ Modifying array while iterating

// WRONG: unpredictable behavior
foreach ($arr as $key => $value) {
    if ($value == 3) unset($arr[$key]); // risky
}

// CORRECT: collect keys first, then delete
$toDelete = [];
foreach ($arr as $key => $value) {
    if ($value == 3) $toDelete[] = $key;
}
foreach ($toDelete as $key) {
    unset($arr[$key]);
}
$arr = array_values($arr);

6. Interview Questions β€” Basics Level


Q1. Reverse an Array [E][FB]

Question: Reverse an array without using built-in reverse function.


🧠 How to Approach This

Step 1 β€” Recognize the pattern:

Reverse = work from both ends simultaneously β†’ two pointers (opposite direction).

Step 2 β€” Brute force:

New array, copy in reverse order β†’ O(n) space. Interviewer often wants O(1) space.

Step 3 β€” Optimal insight:

Two pointers L=0, R=n-1. Swap arr[L] and arr[R], then L++, R--. When L >= R, we're done. No extra space.

Step 4 β€” Algorithm:

1. L=0, R=n-1

2. While L < R: swap(arr[L], arr[R]); L++; R--

Step 5 β€” Edge cases:

- Empty array: nothing to do

- Odd length: middle element stays in place

Way of Thinking:

Use two pointers β€” one at start, one at end. Swap and move both inward until they meet.

[1, 2, 3, 4, 5]
 L           R   β†’ swap(1,5) β†’ [5, 2, 3, 4, 1]
    L     R      β†’ swap(2,4) β†’ [5, 4, 3, 2, 1]
       L=R       β†’ stop

PHP Solution:

function reverseArray(array $arr): array {
    $left = 0;
    $right = count($arr) - 1;

    while ($left < $right) {
        // Swap
        [$arr[$left], $arr[$right]] = [$arr[$right], $arr[$left]];
        $left++;
        $right--;
    }

    return $arr;
}

// Test
print_r(reverseArray([1, 2, 3, 4, 5]));
// Output: [5, 4, 3, 2, 1]

Time: O(n) | Space: O(1)


Q2. Find Max and Min in Array [E][FB]


🧠 How to Approach This

Step 1 β€” Recognize the pattern:

Single-pass scan to find two values simultaneously.

Step 2 β€” Brute force:

Two separate loops, one for max and one for min β†’ O(2n). Combine into one loop.

Step 3 β€” Optimal insight:

Initialize both max and min to the first element. Scan from index 1: update max if current > max, update min if current < min.

Step 4 β€” Edge cases:

- Single element: max = min = that element

- All equal: max = min

Way of Thinking:

Assume first element is max AND min. Loop through rest β€” if you find bigger, update max. If smaller, update min.

function findMaxMin(array $arr): array {
    $max = $arr[0];
    $min = $arr[0];

    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] > $max) $max = $arr[$i];
        if ($arr[$i] < $min) $min = $arr[$i];
    }

    return ['max' => $max, 'min' => $min];
}

print_r(findMaxMin([3, 1, 4, 1, 5, 9, 2, 6]));
// max: 9, min: 1

Time: O(n) | Space: O(1)


Q3. Check if Array is Sorted [E]


🧠 How to Approach This

Step 1 β€” Recognize the pattern:

Single-pass adjacent comparison. Stop as soon as you find a violation.

Step 2 β€” Key insight:

You only need to check adjacent pairs. If arr[i] > arr[i+1] for ANY i, array is not sorted. If you complete the loop with no violations, it is sorted.

Step 3 β€” Edge cases:

- Empty or single element: trivially sorted (return true)

- All same values: sorted (no violation)

Way of Thinking:

If any element is greater than the next β†’ NOT sorted. Loop and compare adjacent.

function isSorted(array $arr): bool {
    for ($i = 0; $i < count($arr) - 1; $i++) {
        if ($arr[$i] > $arr[$i + 1]) {
            return false;
        }
    }
    return true;
}

var_dump(isSorted([1, 2, 3, 4, 5])); // true
var_dump(isSorted([1, 3, 2, 4, 5])); // false

Time: O(n) | Space: O(1)


Q4. Count Occurrences of Each Element [E][FB]


🧠 How to Approach This

Step 1 β€” Recognize the pattern:

Frequency counting = hashmap. O(n) time, O(k) space where k = distinct elements.

Step 2 β€” Key insight:

Use associative array as a map. For each element: if key exists increment it, else initialize to 1.

Step 3 β€” Follow-up questions to anticipate:

"Find most frequent element" β†’ sort by value desc, take first key.

"Find elements appearing more than n/2 times" β†’ Boyer-Moore Voting Algorithm.

Step 4 β€” Edge cases:

- Empty array: return empty map

In PHP: array_count_values($arr) does this in one call.

Way of Thinking:

Use a hash map (associative array). Loop through array β€” if key exists, increment; else set to 1.

function countOccurrences(array $arr): array {
    $count = [];

    foreach ($arr as $value) {
        if (isset($count[$value])) {
            $count[$value]++;
        } else {
            $count[$value] = 1;
        }
    }

    return $count;
    // PHP shortcut: array_count_values($arr)
}

print_r(countOccurrences([1, 2, 2, 3, 3, 3, 4]));
// [1=>1, 2=>2, 3=>3, 4=>1]

Q5. Remove Duplicates from Array [E][FB]


🧠 How to Approach This

Step 1 β€” Choose the right approach:

- If unsorted or order matters: use a hash set to track seen elements. O(n) time + O(n) space.

- If sorted: use two-pointer in-place. O(n) time + O(1) space.

Step 2 β€” Hash set approach:

Walk through array. Add element to result only if not in $seen set. O(n) time.

Step 3 β€” Two-pointer approach (sorted):

slow=0 tracks last unique. fast scans. Write nums[fast] to nums[slow] only when different from nums[slow].

Step 4 β€” PHP built-in:

array_values(array_unique($arr)) β€” mention it, then explain the manual version.

Way of Thinking 1 (PHP built-in):

$arr = [1, 2, 2, 3, 3, 3, 4];
$unique = array_values(array_unique($arr));
// [1, 2, 3, 4]

Way of Thinking 2 (manual β€” show understanding):

Use a hash set (associative array as a set). Loop β€” if not seen before, add to result.

function removeDuplicates(array $arr): array {
    $seen = [];
    $result = [];

    foreach ($arr as $value) {
        if (!isset($seen[$value])) {
            $seen[$value] = true;
            $result[] = $value;
        }
    }

    return $result;
}

print_r(removeDuplicates([1, 2, 2, 3, 3, 3, 4]));
// [1, 2, 3, 4]

Time: O(n) | Space: O(n)


Q6. Rotate Array by K Positions [M][FB]

Question: Rotate array [1,2,3,4,5] by k=2 to get [4,5,1,2,3]


🧠 How to Approach This

Step 1 β€” Recognize the pattern:

Rotate right by k = last k elements move to front. Key insight: use the "reverse trick" for O(1) space.

Step 2 β€” Brute force:

Slice last k elements, concatenate with first n-k β†’ O(n) space.

Step 3 β€” Reverse trick insight:

Three reversals convert the array to its rotated form without extra space:

1. Reverse last k elements

2. Reverse first n-k elements

3. Reverse the entire array

Step 4 β€” Algorithm:

Always do k = k % n first to handle cases where k > n.

Step 5 β€” Edge cases:

- k = 0 or k = n: no change

- k > n: use k % n

Way of Thinking (Reverse Trick β€” O(1) space):

Original: [1, 2, 3, 4, 5], k=2

Step 1: Reverse last k=2 elements
        [1, 2, 3, 5, 4]

Step 2: Reverse first n-k=3 elements
        [3, 2, 1, 5, 4]

Step 3: Reverse entire array
        [4, 5, 1, 2, 3] βœ…
function reverseSubarray(array &$arr, int $start, int $end): void {
    while ($start < $end) {
        [$arr[$start], $arr[$end]] = [$arr[$end], $arr[$start]];
        $start++;
        $end--;
    }
}

function rotateArray(array $arr, int $k): array {
    $n = count($arr);
    $k = $k % $n; // handle k > n

    reverseSubarray($arr, $n - $k, $n - 1); // reverse last k
    reverseSubarray($arr, 0, $n - $k - 1);  // reverse first n-k
    reverseSubarray($arr, 0, $n - 1);        // reverse all

    return $arr;
}

print_r(rotateArray([1, 2, 3, 4, 5], 2));
// [4, 5, 1, 2, 3]

Time: O(n) | Space: O(1)