Array Operations

Back

Loading concept...

🎒 PHP Arrays: Your Magic Backpack!

Imagine you have a magic backpack that can hold anything you want—toys, snacks, books, or treasures. In PHP, an array is exactly like that backpack! It’s a container that holds many things at once, and you can add, remove, find, or organize items whenever you want.

Let’s go on an adventure and learn how to use this magic backpack!


🎨 Array Creation: Packing Your Backpack

Before your adventure, you need to pack your backpack. There are two ways to create arrays in PHP:

The Square Brackets Way (Modern & Cool)

$fruits = ["apple", "banana", "orange"];
$numbers = [1, 2, 3, 4, 5];

The array() Way (Old School)

$fruits = array("apple", "banana", "orange");

Named Pockets (Associative Arrays)

Your backpack has pockets with names on them!

$pet = [
    "name" => "Buddy",
    "type" => "dog",
    "age" => 3
];

Think of => as a little arrow pointing to what’s inside each pocket.


🔍 Array Access and Modification: Finding Your Stuff

Each item in your backpack has a number—like a locker number! The first item is at position 0 (computers start counting from zero).

Getting Items Out

$fruits = ["apple", "banana", "orange"];

echo $fruits[0];  // apple (first item)
echo $fruits[1];  // banana (second item)
echo $fruits[2];  // orange (third item)

Changing Items

Don’t want an apple? Swap it for a grape!

$fruits[0] = "grape";
// Now: ["grape", "banana", "orange"]

Named Pockets Access

$pet = ["name" => "Buddy", "age" => 3];

echo $pet["name"];  // Buddy
$pet["age"] = 4;    // Happy birthday, Buddy!

📦 Push, Pop, Shift, Unshift: Adding & Removing Items

Think of your backpack as having a top and a bottom:

graph TD A["TOP of backpack"] --> B["🍎 apple"] B --> C["🍌 banana"] C --> D["🍊 orange"] D --> E["BOTTOM of backpack"]

Push: Add to the Top

$fruits = ["apple", "banana"];
array_push($fruits, "orange");
// Result: ["apple", "banana", "orange"]

Shortcut:

$fruits[] = "grape";
// Adds "grape" at the end!

Pop: Remove from the Top

$last = array_pop($fruits);
// $last = "grape"
// $fruits = ["apple", "banana", "orange"]

Unshift: Add to the Bottom

array_unshift($fruits, "mango");
// Result: ["mango", "apple", "banana", "orange"]

Shift: Remove from the Bottom

$first = array_shift($fruits);
// $first = "mango"
// $fruits = ["apple", "banana", "orange"]

🎯 Memory Trick:

  • Push/Pop = Top of stack (like stacking plates)
  • Shift/Unshift = Front of line (like a queue)

✂️ Array Slicing and Splicing: Cutting & Pasting

Slicing: Taking a Piece

Imagine cutting a slice of cake—you’re taking a portion without changing the original!

$colors = ["red", "blue", "green", "yellow", "purple"];

$slice = array_slice($colors, 1, 2);
// $slice = ["blue", "green"]
// Takes 2 items, starting from position 1
graph TD A["Original: red, blue, green, yellow, purple"] --> B["slice#40;1, 2#41;"] B --> C["Result: blue, green"]

Splicing: Surgery on Your Array!

This one is powerful—it can remove items, add new ones, or both!

$animals = ["cat", "dog", "bird", "fish"];

// Remove "dog" and "bird", add "hamster"
array_splice($animals, 1, 2, ["hamster"]);

// Result: ["cat", "hamster", "fish"]

Parameters explained:

  1. 1 = Start at position 1
  2. 2 = Remove 2 items
  3. ["hamster"] = Insert these instead

🔎 Array Searching: Finding Lost Treasures

You lost your toy in the backpack. Let’s find it!

in_array(): Is It There?

$toys = ["car", "ball", "doll", "robot"];

if (in_array("ball", $toys)) {
    echo "Found the ball!";
}

array_search(): Where Exactly?

$position = array_search("doll", $toys);
// $position = 2 (it's at position 2!)

array_key_exists(): Check Named Pockets

$user = ["name" => "Sam", "age" => 10];

if (array_key_exists("name", $user)) {
    echo "Name pocket exists!";
}

⚡ Tip: array_search() returns false if not found. Always use === to check:

if (array_search("xyz", $toys) === false) {
    echo "Not found!";
}

🔑 Array Keys and Values: Labels and Contents

Every pocket has a label (key) and stuff inside (value).

Get All Keys (Labels)

$pet = ["name" => "Fluffy", "type" => "cat"];

$labels = array_keys($pet);
// $labels = ["name", "type"]

Get All Values (Stuff)

$stuff = array_values($pet);
// $stuff = ["Fluffy", "cat"]

Flip Keys and Values

Sometimes you want the label to become the content!

$grades = ["A" => "Excellent", "B" => "Good"];

$flipped = array_flip($grades);
// $flipped = ["Excellent" => "A", "Good" => "B"]

📊 Array Sorting: Organizing Your Stuff

A messy backpack is no fun! Let’s organize.

sort(): A to Z (or small to big)

$numbers = [3, 1, 4, 1, 5];
sort($numbers);
// Result: [1, 1, 3, 4, 5]

rsort(): Z to A (reverse)

$letters = ["c", "a", "b"];
rsort($letters);
// Result: ["c", "b", "a"]

asort(): Sort Values, Keep Keys

$scores = ["Sam" => 85, "Alex" => 92, "Kim" => 78];
asort($scores);
// ["Kim" => 78, "Sam" => 85, "Alex" => 92]

ksort(): Sort by Keys

$items = ["b" => "ball", "a" => "apple"];
ksort($items);
// ["a" => "apple", "b" => "ball"]
graph TD A["sort"] --> B["Values only, loses keys"] C["asort"] --> D["Values, keeps keys"] E["ksort"] --> F["Sorts by key names"] G["rsort"] --> H["Reverse order"]

đź”— Array Merging and Combining: Team Up!

Two backpacks are better than one!

array_merge(): Combine Everything

$bag1 = ["apple", "banana"];
$bag2 = ["orange", "grape"];

$bigBag = array_merge($bag1, $bag2);
// ["apple", "banana", "orange", "grape"]

With Named Pockets

Later values win if keys are the same!

$info1 = ["name" => "Sam", "age" => 10];
$info2 = ["age" => 11, "city" => "NYC"];

$merged = array_merge($info1, $info2);
// ["name" => "Sam", "age" => 11, "city" => "NYC"]

array_combine(): Zipper Magic!

Make one array the keys, another the values—like zipping two sides together!

$names = ["a", "b", "c"];
$fruits = ["apple", "banana", "cherry"];

$result = array_combine($names, $fruits);
// ["a" => "apple", "b" => "banana", "c" => "cherry"]

Spread Operator (PHP 7.4+)

A cool modern way to merge:

$all = [...$bag1, ...$bag2];
// Same as array_merge!

🎉 You Did It!

You now know how to:

Skill What You Learned
📦 Create Make arrays with [] or array()
🔍 Access Get items with $arr[0] or $arr["key"]
âž• Add/Remove push, pop, shift, unshift
✂️ Slice/Splice Cut portions or do surgery
🔎 Search in_array(), array_search()
🔑 Keys/Values array_keys(), array_values()
📊 Sort sort(), rsort(), asort(), ksort()
đź”— Merge array_merge(), array_combine()

Your magic backpack is now fully organized and ready for any adventure. Go build something amazing! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.