PHP Intermediate

PHP Arrays - Indexed and Associative Arrays

CodingerWeb
CodingerWeb
25 views 60 min read

PHP Arrays

Arrays are variables that can store multiple values in a single variable. PHP supports different types of arrays for various use cases.

Creating Arrays

Multiple ways to create arrays in PHP:

<?php
// Using array() function
$fruits = array("apple", "banana", "orange");

// Using short syntax (PHP 5.4+)
$colors = ["red", "green", "blue"];

// Empty array
$empty = [];
$empty2 = array();

// Mixed data types
$mixed = ["John", 25, true, 3.14];
?>

Indexed Arrays

Arrays with numeric indexes (starting from 0):

<?php
$fruits = ["apple", "banana", "orange"];

// Accessing elements
echo $fruits[0]; // apple
echo $fruits[1]; // banana
echo $fruits[2]; // orange

// Adding elements
$fruits[3] = "grape";
$fruits[] = "kiwi"; // Automatically assigns next index

// Modifying elements
$fruits[0] = "pineapple";

print_r($fruits);
/*
Array
(
    [0] => pineapple
    [1] => banana
    [2] => orange
    [3] => grape
    [4] => kiwi
)
*/
?>

Associative Arrays

Arrays with named keys:

<?php
// Creating associative array
$person = [
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York",
    "email" => "john@example.com"
];

// Accessing elements
echo $person["name"]; // John Doe
echo $person["age"];  // 30

// Adding/modifying elements
$person["phone"] = "123-456-7890";
$person["age"] = 31;

// Alternative syntax
$student = array(
    "id" => 12345,
    "name" => "Alice Smith",
    "grade" => "A"
);
?>

Multidimensional Arrays

Arrays containing other arrays:

<?php
// 2D array
$students = [
    ["John", 85, "Math"],
    ["Alice", 92, "Science"],
    ["Bob", 78, "History"]
];

// Accessing elements
echo $students[0][0]; // John
echo $students[1][1]; // 92

// Associative multidimensional array
$employees = [
    "john" => [
        "name" => "John Doe",
        "position" => "Developer",
        "salary" => 75000
    ],
    "alice" => [
        "name" => "Alice Smith",
        "position" => "Designer",
        "salary" => 65000
    ]
];

echo $employees["john"]["name"]; // John Doe
echo $employees["alice"]["salary"]; // 65000
?>

Array Functions

Basic Array Functions

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

// Count elements
echo count($numbers); // 5
echo sizeof($numbers); // 5 (alias of count)

// Check if array
var_dump(is_array($numbers)); // bool(true)

// Check if key exists
$person = ["name" => "John", "age" => 30];
var_dump(array_key_exists("name", $person)); // bool(true)
var_dump(isset($person["email"])); // bool(false)

// Check if value exists
var_dump(in_array("John", $person)); // bool(true)
var_dump(in_array(30, $person)); // bool(true)
?>

Adding and Removing Elements

<?php
$fruits = ["apple", "banana"];

// Add to end
array_push($fruits, "orange", "grape");
$fruits[] = "kiwi"; // Alternative

// Add to beginning
array_unshift($fruits, "mango");

// Remove from end
$lastFruit = array_pop($fruits);
echo $lastFruit; // kiwi

// Remove from beginning
$firstFruit = array_shift($fruits);
echo $firstFruit; // mango

// Remove specific element
unset($fruits[1]); // Removes element at index 1

print_r($fruits);
?>

Array Sorting

<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];

// Sort ascending
sort($numbers);
print_r($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]

// Sort descending
rsort($numbers);
print_r($numbers); // [9, 6, 5, 4, 3, 2, 1, 1]

// Associative array sorting
$ages = ["John" => 30, "Alice" => 25, "Bob" => 35];

// Sort by value (keep keys)
asort($ages); // Alice=>25, John=>30, Bob=>35

// Sort by key
ksort($ages); // Alice=>25, Bob=>35, John=>30

// Reverse sorts
arsort($ages); // Sort by value descending
krsort($ages); // Sort by key descending

// Custom sorting
$students = [
    ["name" => "John", "grade" => 85],
    ["name" => "Alice", "grade" => 92],
    ["name" => "Bob", "grade" => 78]
];

usort($students, function($a, $b) {
    return $b["grade"] - $a["grade"]; // Sort by grade descending
});
?>

Array Manipulation

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

// Array slice
$slice = array_slice($numbers, 1, 3); // [2, 3, 4]

// Array splice (remove and replace)
$removed = array_splice($numbers, 1, 2, ["a", "b"]);
// $numbers is now [1, "a", "b", 4, 5]
// $removed is [2, 3]

// Array merge
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2); // [1, 2, 3, 4, 5, 6]

// Array combine (keys from one, values from another)
$keys = ["name", "age", "city"];
$values = ["John", 30, "NYC"];
$combined = array_combine($keys, $values);
// ["name" => "John", "age" => 30, "city" => "NYC"]

// Array flip (swap keys and values)
$original = ["a" => 1, "b" => 2, "c" => 3];
$flipped = array_flip($original); // [1 => "a", 2 => "b", 3 => "c"]
?>

Array Filtering and Mapping

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter even numbers
$evens = array_filter($numbers, function($n) {
    return $n % 2 == 0;
});
print_r($evens); // [2, 4, 6, 8, 10]

// Map - square each number
$squares = array_map(function($n) {
    return $n * $n;
}, $numbers);
print_r($squares); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

// Reduce - sum all numbers
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum; // 55

// Array walk - modify array in place
array_walk($numbers, function(&$value, $key) {
    $value = $value * 2;
});
print_r($numbers); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
?>

Array Iteration

Different ways to loop through arrays:

<?php
$fruits = ["apple", "banana", "orange"];

// For loop (indexed arrays)
for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . "
";
}

// Foreach loop
foreach ($fruits as $fruit) {
    echo $fruit . "
";
}

// Foreach with index
foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit
";
}

// Associative array iteration
$person = ["name" => "John", "age" => 30, "city" => "NYC"];

foreach ($person as $key => $value) {
    echo "$key: $value
";
}
?>

Array Keys and Values

<?php
$person = ["name" => "John", "age" => 30, "city" => "NYC"];

// Get all keys
$keys = array_keys($person); // ["name", "age", "city"]

// Get all values
$values = array_values($person); // ["John", 30, "NYC"]

// Search for key by value
$key = array_search("John", $person); // "name"

// Get random key(s)
$randomKey = array_rand($person); // Random key
$randomKeys = array_rand($person, 2); // Array of 2 random keys
?>

Practical Examples

Shopping Cart

<?php
class ShoppingCart {
    private $items = [];
    
    public function addItem($name, $price, $quantity = 1) {
        if (isset($this->items[$name])) {
            $this->items[$name]["quantity"] += $quantity;
        } else {
            $this->items[$name] = [
                "price" => $price,
                "quantity" => $quantity
            ];
        }
    }
    
    public function removeItem($name) {
        unset($this->items[$name]);
    }
    
    public function getTotal() {
        $total = 0;
        foreach ($this->items as $item) {
            $total += $item["price"] * $item["quantity"];
        }
        return $total;
    }
    
    public function getItems() {
        return $this->items;
    }
}

$cart = new ShoppingCart();
$cart->addItem("Apple", 1.50, 3);
$cart->addItem("Banana", 0.75, 2);
echo "Total: $" . $cart->getTotal(); // Total: $6.00
?>

Grade Calculator

<?php
function calculateGrades($students) {
    $results = [];
    
    foreach ($students as $name => $scores) {
        $average = array_sum($scores) / count($scores);
        $grade = getLetterGrade($average);
        
        $results[$name] = [
            "scores" => $scores,
            "average" => round($average, 2),
            "grade" => $grade
        ];
    }
    
    return $results;
}

function getLetterGrade($average) {
    if ($average >= 90) return "A";
    if ($average >= 80) return "B";
    if ($average >= 70) return "C";
    if ($average >= 60) return "D";
    return "F";
}

$students = [
    "John" => [85, 92, 78, 96],
    "Alice" => [88, 91, 87, 93],
    "Bob" => [72, 68, 75, 71]
];

$grades = calculateGrades($students);
print_r($grades);
?>

Practice Exercise

Create a program that:

  • Stores information about books (title, author, price, genre)
  • Allows adding, removing, and searching books
  • Calculates total value of all books
  • Sorts books by different criteria

Key Takeaways

  • Arrays can store multiple values in one variable
  • Use indexed arrays for ordered data
  • Use associative arrays for key-value pairs
  • PHP provides many built-in array functions
  • Choose the right array type for your data structure