Notes

Arrays in various languages

Edit on GitHub

Programming
2 minutes

PHP

Use print_r() instead of echo to print entire arrays. echo can be used to get single values

1<?php
2  // Array (index based)
3  $color = array('red', 'green', 'yellow', 'blue');
4
5  print_r( $colors );
6?>
Array
(
    [0] => red
    [1] => green
    [2] => yellow
    [3] => blue
)
1// Associative Arrays (strings as keys)
2$johnny = array(
3  'name' => 'Johny',
4  'age' => 32,
5  'job' => 'Software Engineer',
6);
7
8print_r( $johnny );
Array
(
    [name] => Johny
    [age] => 32
    [job] => Software Engineer
)
1echo $johnny['job']; // Software Engineer
 1// Multidimensional (nested) Arrays (index based)
 2$employees = array(
 3  $johnny = array(
 4    'name' => 'Johny',
 5    'age' => 32,
 6    'job' => 'Software Engineer',
 7  ),
 8    $jack = array(
 9    'name' => 'Jack',
10    'age' => 26,
11    'job' => 'Marketing Manager',
12  ),
13    $jane = array(
14    'name' => 'Jane',
15    'age' => 23,
16    'job' => 'Project Manager',
17  ),
18);
19
20print_r( $employees );
Array
(
    [0] => Array
        (
            [name] => Johny
            [age] => 32
            [job] => Software Engineer
        )

    [1] => Array
        (
            [name] => Jack
            [age] => 26
            [job] => Marketing Manager
        )

    [2] => Array
        (
            [name] => Jane
            [age] => 23
            [job] => Project Manager
        )

)
 1// Multidimensional (nested) Arrays (strings as keys)
 2$employees = array(
 3 'johnny' => array(
 4    'name' => 'Johny',
 5    'age' => 32,
 6    'job' => 'Software Engineer',
 7  ),
 8  'jack' => array(
 9    'name' => 'Jack',
10    'age' => 26,
11    'job' => 'Marketing Manager',
12  ),
13  'jane' => array(
14    'name' => 'Jane',
15    'age' => 23,
16    'job' => 'Project Manager',
17  ),
18);
19
20print_r( $employees );
Array
(
    [johnny] => Array
        (
            [name] => Johny
            [age] => 32
            [job] => Software Engineer
        )

    [jack] => Array
        (
            [name] => Jack
            [age] => 26
            [job] => Marketing Manager
        )

    [jane] => Array
        (
            [name] => Jane
            [age] => 23
            [job] => Project Manager
        )

)
1print_r($employees['jane']);
Array
(
    [name] => Jane
    [age] => 23
    [job] => Project Manager
)
1echo $employees['jane']; // PHP Warning:  Array to string conversion in /workspace/Main.php on line 40
1print_r($employees['jane']['job']);
2
3// OR
4echo $employees['jane']['job'];