0017

How to write PHP and Javascript arrays

How to write PHP and Javascript arrays

2012.12.16

I’m not good at arrays, probably because there are a lot of parentheses and it’s too complicated. I wrote down how to write array data in PHP and Javascript, which I often use. The following table shows you how to use it.

In the case of Javascript

 //simple array
var val1 = [
'value1',
'value2',
'value3' //no comma at the end
]
alert(val1[0]); //value1

//Associative array
var val2 = {
'key1':'hoge1',
'key2':'hoge2',
'key3':'hoge3' //no comma at the end
};
alert(val2.key1); //hoge1

// An array of arrays
var val3 = {

hoge0:{
key1: ah,
key2:i. key3:u //no comma at the end
key3:U //no comma at the end
},
hoge1:{ key1:{
key1:e. key2:oh,
key2:O. key3:ka
key3:ka, //no comma at the end
},
hoge2:{
key1:k, hoge2:{key1:ki, hoge2:k
key2:ku, key2:ku, //no comma at the end,
key3:{key1:ki, key2:ku, key3:ke, //no comma at the end
} //No comma at the end

};
alert(val3.foo1.key1); //eh

In the case of PHP

As in “Recommendations for writing arrays in PHP source code : akiyan.com”, W The following code is a quote.

 // A simple array
$value = array(
'value1',
'value2',
'value3',
);

// Associative array
$value = array(
'key1' => 'value1',
'key2' => 'value2',
'hogehoge' => 'value3',
);

// An array of arrays
$value = array(
'key1' => 'value1',
'key2' => 'value2',
'hogehoge' => array(
'foo',
'Bar',
'hoge',
),
);