forked from bradtraversy/php-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03_arrays.php
87 lines (67 loc) · 1.62 KB
/
03_arrays.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/* ----------- Arrrays ----------- */
/*
If you need to store multiple values, you can use arrays. Arrays hold "elements"
*/
// Simple array of numbers
$numbers = [1, 2, 3, 4, 5];
// Simple array of strings
$colors = ['red', 'blue', 'green'];
// Using the array function to create an array of numbers
$numbers = [1, 2, 3, 4, 5];
// Outputting values from an array
echo $numbers[0];
echo $numbers[3] + $numbers[4];
// We can use print_r or var_dump to see the contents of an array
var_dump($numbers);
/* ------ Associative Arrays ----- */
/*
Associative arrays allow us to use named keys to identify values.
*/
$colors = [
1 => 'red',
2 => 'green',
3 => 'blue',
];
// echo $colors[1];
// Strings as keys
$hex = [
'red' => '#f00',
'green' => '#0f0',
'blue' => '#00f',
];
echo $hex['red'];
var_dump($hex);
/* ---- Multi-dimensional arrays ---- */
/*
Multi-dimansional arrays are often used to store data in a table format.
*/
// Single person
$person1 = [
'first_name' => 'Brad',
'last_name' => 'Traversy',
'email' => '[email protected]',
];
// Array of people
$people = [
$person1, // [...$person1]
[
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '[email protected]',
],
[
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => '[email protected]',
],
];
var_dump($people);
// Accessing values in a multi-dimensional array
echo $people[0]['first_name'];
echo $people[2]['email'];
// Encode to JSON
var_dump(json_encode($people));
// Decode from JSON
$jsonobj = '{"first_name":"Brad","last_name": "Traversy","email":"[email protected]"}';
var_dump(json_decode($jsonobj));