Creating Index-Based and Associative Arrays in PHP

Arrays in PHP can be created in two primary ways:
1️⃣ Index-Based (Numeric) Arrays
2️⃣ Associative Arrays

Both are essential for organizing data efficiently in PHP applications.


1. Creating Index-Based (Numeric) Arrays

Index-based arrays store values using numeric keys, starting from 0 by default.


a) Using Array Literal []

$colors = ["Red", "Blue", "Green"];

Accessing Elements

echo $colors[0]; // Red
echo $colors[2]; // Green

b) Using array() Function

$fruits = array("Apple", "Mango", "Banana");

c) Manually Assigning Indexes

$numbers = [];
$numbers[0] = 100;
$numbers[1] = 200;
$numbers[5] = 500; // Skips indexes 2–4

d) Adding Values Automatically

$animals = [];
$animals[] = "Dog";
$animals[] = "Cat";
$animals[] = "Horse";

2. Creating Associative Arrays

Associative arrays use string keys instead of numeric indexes.


a) Inline Declaration

$user = [
    "name" => "Sagar",
    "age" => 25,
    "role" => "Developer"
];

b) Using array()

$product = array(
    "id" => 101,
    "name" => "Laptop",
    "price" => 55000
);

c) Adding Values Dynamically

$student = [];
$student["name"] = "Amit";
$student["class"] = "12th";
$student["marks"] = 85;

3. Accessing Associative Array Values

echo $user["name"];  // Sagar
echo $product["price"]; // 55000

4. Example: Combining Both Types

$details = [
    "id" => 1,
    "skills" => ["PHP", "JavaScript", "SQL"]
];

echo $details["skills"][1]; // JavaScript

Conclusion

Creating arrays—whether index-based or associative—is fundamental in PHP.
They help structure data more clearly and make your applications more organized and efficient.


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *