-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10_array.php
92 lines (75 loc) · 1.92 KB
/
10_array.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
88
89
90
91
92
<?php
/* ----------- Arrays ----------- */
/*
If you need to store multiple values, you can use arrays. Arrays hold "elements"
*/
echo "<pre/>======== Simple Arrays ======== <pre/>";
// Simple array of numbers
$numbers = [1, 2, 3, 4, 5];
// Simple array of strings
$colors = ['red', 'blue', 'green'];
// Outputting values from an array
echo $numbers[0];
echo "<pre/>";
echo $numbers[3] + $numbers[4];
// We can use print_r or var_dump to see the contents of an array
echo '<pre>';
print_r($numbers);
echo "<pre/>======== Associative Arrays ======== <pre/>";
/*
Associative arrays allow us to use named keys to identify values.
*/
$colors = [
1 => 'red',
2 => 'green',
3 => 'blue',
];
echo $colors[1];
echo '<pre>';
// Strings as keys
$hex = [
'red' => '#f00',
'green' => '#0f0',
'blue' => '#00f',
];
echo $hex['red'];
echo '<pre>';
print_r($hex);
echo "<pre/>======== Multi-dimensional arrays ======== <pre/>";
/*
Multi-dimensional arrays are often used to store data in a table format.
*/
// Single person
$person1 = [
'first_name' => 'Hridoy',
'last_name' => 'Ahmed',
'email' => 'codewithhridoy@gmail.com',
];
// Array of people
$people = [
$person1, // [...$person1]
[
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@gmail.com',
],
[
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => 'jane@gmail.com',
],
];
echo '<pre>';
print_r($people);
echo '<pre>';
echo "<pre/>======== Accessing values in a multi-dimensional array ======== <pre/>";
echo $people[0]['first_name'];
echo '<pre>';
echo $people[2]['email'];
echo '<pre>';
echo "<pre/>======== Encode to JSON ======== <pre/>";
print_r(json_encode($people));
echo "<pre/>======== Decode from JSON ======== <pre/>";
$json_obj = '{"first_name":"Hridoy","last_name": "Ahmed","email":"codewithhridoy@gmail.com"}';
echo '<pre>';
print_r(json_decode($json_obj));