Cottient
Cottient

Reputation: 164

How to reference array in an array in PHP

I want to make an array like the one below:

$database = array(
    array(
        "key" => "Key1",
        "hwid" => "Hwid1"
    ),
    array(
        "key" => "Key2",
        "hwid" => "Hwid2"
    ),
);

How would I go about making this by inserting values. Here is what I have tried:

$array = array();
$array[array()["key"]] = "Key1";
$array[array()["hwid"]] = "HWID1";

Sadly the above code does not make the structure of the array that I wanted. How would I achieve this?

Upvotes: 0

Views: 52

Answers (3)

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

$array = array();
$arr1 = ["id" => "id1", "hwid" => "hwid1"];
$arr2 = ["id" => "id2", "hwid" => "hwid2"];
array_push($array, $arr1, $arr2);
var_dump($array);

You don't need array index to be an array

Upvotes: 1

Saeed M.
Saeed M.

Reputation: 2361

Your parent array is not associative, the only way you can access to it is by int index which starts with 0:

try this:

$array = array();
$array[0]["key"] = "Key1";
$array[0]["hwid"] = "HWID1";

Upvotes: 0

bassxzero
bassxzero

Reputation: 5041

$array = [];
$array[] = ["key" => "Key1","hwid" => "Hwid1"];
$array[] = ["key" => "Key2","hwid" => "Hwid2"];

or

$array = [
    ["key" => "Key1","hwid" => "Hwid1"],
    ["key" => "Key2","hwid" => "Hwid2"]
];

Upvotes: 1

Related Questions