PHP Arrays - Associative and Multidimensional Arrays - Codingque

PHP Arrays: Associative and Multidimensional

Explore associative and multidimensional arrays in PHP with practical examples and explanations.

Introduction to PHP Arrays

Arrays in PHP are used to store multiple values in a single variable. They come in various types, including indexed, associative, and multidimensional arrays. In this guide, we'll cover associative and multidimensional arrays.

1. Associative Arrays

Associative arrays use named keys that you assign to them. They are useful when you want to access array elements by a specific key rather than by an index.

<?php
// Creating an associative array
$person = array(
    "first_name" => "John",
    "last_name" => "Doe",
    "age" => 30,
    "email" => "[email protected]"
);

// Accessing elements
echo "First Name: " . $person["first_name"] . "<br>";
echo "Last Name: " . $person["last_name"] . "<br>";
echo "Age: " . $person["age"] . "<br>";
echo "Email: " . $person["email"];
?>

Explanation: The $person array is an associative array where each key (like first_name, last_name) is associated with a value. You access elements using their keys.

2. Multidimensional Arrays

Multidimensional arrays are arrays of arrays. They allow you to store more complex data structures, such as tables or matrices.

<?php
// Creating a multidimensional array
$contacts = array(
    array("name" => "John", "phone" => "123-456-7890"),
    array("name" => "Jane", "phone" => "987-654-3210"),
    array("name" => "Doe", "phone" => "456-789-0123")
);

// Accessing elements
echo "Contact 1: " . $contacts[0]["name"] . " - " . $contacts[0]["phone"] . "<br>";
echo "Contact 2: " . $contacts[1]["name"] . " - " . $contacts[1]["phone"] . "<br>";
echo "Contact 3: " . $contacts[2]["name"] . " - " . $contacts[2]["phone"];
?>

Explanation: The $contacts array is a multidimensional array where each element is itself an associative array. This structure allows storing and accessing complex datasets.

3. Nested Arrays

Nested arrays are arrays within arrays, useful for representing more complex structures such as lists of lists.

<?php
// Creating a nested array
$departments = array(
    "HR" => array("Alice", "Bob"),
    "IT" => array("Charlie", "David"),
    "Sales" => array("Eve", "Frank")
);

// Accessing elements
echo "HR Department: " . implode(", ", $departments["HR"]) . "<br>";
echo "IT Department: " . implode(", ", $departments["IT"]) . "<br>";
echo "Sales Department: " . implode(", ", $departments["Sales"]);
?>

Explanation: The $departments array is a nested array where each key corresponds to another array. The implode() function is used to convert array elements into a string.

Previous Next
Modern Footer