Arrays

Arrays are PHP’s most important composite type: an ordered map of keys (ints or strings) to values. They power lists, dictionaries, JSON data, tables, and more.

1) Creating Arrays

<?php
  // Short syntax (recommended)
  $nums = [10, 20, 30];                   // indexed
  $user = ["name"=>"Sonu", "age"=>25]; // associative

  // Long syntax (legacy)
  $old = array(1, 2, 3);

  // Auto-incrementing keys
  $a = [];
  $a[] = "x"; $a[] = "y"; // keys 0,1

  // Multidimensional
  $matrix = [[1,2],[3,4]];
?>

Adding & Removing

<?php
  $q = [];
  array_push($q, "a", "b"); // push to end
  $last = array_pop($q);        // pop from end
  array_unshift($q, "start"); // add to beginning
  $first = array_shift($q);    // remove from beginning
?>

2) Destructuring (list / array destructuring)

<?php
  // Positional
  [$x, $y] = [10, 20]; // $x=10, $y=20

  // With keys (PHP 7.1+)
  ['name' => $name, 'age' => $age] =
    ['name'=>'Sonu', 'age'=>25, 'city'=>'Patna'];

  // Skipping values
  [$a, , $c] = [1,2,3];
?>

3) Spread / Unpacking (...)

Unpack one array into another (PHP 7.4+). Keys are preserved for string keys; integer keys are reindexed.

<?php
  $base = [1, 2];
  $more = [3, 4];
  $all  = [...$base, 100, ...$more]; // [1,2,100,3,4]

  // Associative: later keys override earlier keys when using array_merge/array_replace; unpacking keeps string keys as-is
  $a1 = ['name'=>'A', 'age'=>20];
  $a2 = ['age'=>22];
  $u  = [...$a1, ...$a2]; // ['name'=>'A','age'=>22]
?>

4) Slicing, Chunking, Splicing

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

  // slice: non-destructive copy
  $slice = array_slice($arr, 1, 2); // [20,30]

  // chunk
  $chunks = array_chunk($arr, 2);   // [[10,20],[30,40],[50]]

  // splice: remove/replace in-place
  $removed = array_splice($arr, 1, 2, [99]);
  // $arr becomes [10,99,40,50]; $removed is [20,30]
?>

5) Searching

<?php
  $colors = ['red','green','blue'];
  var_dump( in_array('green', $colors, true) ); // true; strict
  $idx = array_search('blue', $colors, true); // index

  $user = ['name'=>'Sonu'];
  var_dump( array_key_exists('name', $user) );  // true
  var_dump( isset($user['age']) );            // false (not set)
?>
Tip: Use the third parameter = true for strict type comparison in in_array/array_search.

6) Sorting (value, key, custom)

FunctionSortsPreserves Keys?
sort / rsortValuesNo (reindex)
asort / arsortValuesYes
ksort / krsortKeysYes
usortValues (custom)No
uasortValues (custom)Yes
uksortKeys (custom)Yes
natsort / natcasesortNatural orderYes
<?php
  $scores = ['A'=>90, 'B'=>75, 'C'=>82];
  asort($scores);    // by value ascending, keep keys
  arsort($scores);   // by value desc
  ksort($scores);    // by key ascending

  // Custom: sort products by price then name
  $products = [['name'=>'Pen','price'=>10],['name'=>'Pencil','price'=>10],['name'=>'Book','price'=>50]];
  usort($products, function($a, $b) {
    $cmp = $a['price'] <=> $b['price'];
    return $cmp ?: ($a['name'] <=> $b['name']);
  });
?>
Gotcha: sort()/usort() reindex numeric keys. If you need to preserve keys, use asort()/uasort().

7) Map / Filter / Reduce

<?php
  $nums = [1,2,3,4];

  // map
  $squares = array_map(fn($x) => $x*$x, $nums);

  // filter
  $even = array_filter($nums, fn($x) => $x % 2 == 0);

  // reduce
  $sum = array_reduce($nums, fn($acc, $x) => $acc + $x, 0);

  // walk (in-place)
  $names = ['sonu','amit'];
  array_walk($names, function(&$v) { $v = ucfirst($v); });
?>

8) Merging, Union, Replace

<?php
  $a = [1,2];
  $b = [3];
  $m1 = array_merge($a, $b);   // [1,2,3]; reindexes numeric keys
  $m2 = $a + $b;                 // union: keeps left keys on conflict

  // Associative merging
  $u1 = array_merge(['name'=>'A'], ['name'=>'B']); // name = B
  $u2 = array_replace(['name'=>'A'], ['name'=>'B']); // also B
?>
When to use:
  • array_merge to append lists and override associative values.
  • + union to fill missing keys from the right while keeping left values.
  • array_replace to replace by keys (deep variant: array_replace_recursive).

9) Set Operations

<?php
  $a = [1,2,3];
  $b = [3,4];

  $diff = array_diff($a, $b);            // [1,2]
  $inter = array_intersect($a, $b);       // [3]
  $udiff = array_udiff($a, $b, fn($x,$y) => $x<=>$y);
?>

10) Columns, Keys, Values, Combine

<?php
  $users = [['id'=>1,'name'=>'Sonu'],['id'=>2,'name'=>'Amit']];
  $names = array_column($users, 'name');     // ['Sonu','Amit']
  $mapById = array_column($users, null, 'id'); // [1=>user1, 2=>user2]

  $keys   = array_keys($mapById);
  $values = array_values($mapById);

  $k = ['a','b']; $v = [10,20];
  $combined = array_combine($k, $v); // ['a'=>10,'b'=>20]

  $unique = array_unique([1,1,2]); // [1,2]
  $counts = array_count_values(["a","b","a"]); // ['a'=>2,'b'=>1]
?>

11) Performance & Pitfalls

IssueExplanationFix
Reindexing on sort()/usort() Numeric keys lost Use asort()/uasort() to preserve keys
Modifying during foreach Push/pop affects iteration Iterate a copy or collect changes
By-reference foreach leaks Reference variable stays bound unset($v) after loop
Large arrays = high memory Arrays are hash-maps; overhead per element Use generators, streaming, or chunk processing
Union (+) surprises Left keys win; values on the right dropped Use array_merge/array_replace when overriding
<?php
  // Safe iteration into a new array
  $out = [];
  foreach ($nums as $n) { $out[] = $n*2; }
?>

Practice Tasks

  1. Given $users (array of ['id','name','age']), build [id => name] using array_column.
  2. Merge two config arrays so that keys from the second override the first. Compare array_merge vs +.
  3. Use array_filter to keep only products priced ≥ 500, then array_map to add 18% tax.
  4. Split a list of 10,000 emails into chunks of 100 using array_chunk.
  5. Sort an associative array by value descending while preserving keys; then by key ascending.
Next: Continue with Strings — concatenation, interpolation, common functions, HEREDOC/NOWDOC, and multibyte safety.