5

I'm trying to understand arrays better. Pardon my elementary questions as I just opened my first php book three weeks ago.

I get that you can retrieve key/value pairs using a foreach (or for loop) as below.

 $stockprices= array("Google"=>"800", "Apple"=>"400", "Microsoft"=>"4",  "RIM"=>"15",  "Facebook"=>"30");

foreach ($stockprices as $key =>$price)

What I get confused about are multi dimensional arrays like this one:

$states=(array([0]=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1),
              [1]=>array("capital"=> "Austin", "joined_union"=>1845,"population_rank"=> 2),
              [2]=>array("capital"=> "Boston", "joined_union"=>1788,"population_rank"=> 14)
              ));

My first question is really basic: I know that "capital', "joined_union", "population_rank" are keys and "Sacramento", "1850", "1" are values (correct?). But what do you call [0][1][2]? Are they "main keys" and "capital" etc. sub-keys? I can't find any definition for those; neither in books nor online.

The main question is how do I retrieve Arrays [0][1][2]? Say I want to get the array that joined_union in 1845 (or even trickier during the 1800s), then remove that array.

Finally, can I name Arrays [0][1][2] as California, Texas and Massachusetts correspondingly?

$states=(array("California"=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1),
              "Texas"=>array("capital"=> "Austin", "joined_union"=>1845,"population_rank"=> 2),
              "Massachusetts"=>array("capital"=> "Boston", "joined_union"=>1788,"population_rank"=> 14)
              ));
Patty
  • 85
  • 8
  • 1
    A much cleaner way is to use objects. Read about [object oriented PHP](http://php.net/manual/en/language.oop5.php) and you can avoid the "array-mania". – CodeZombie May 09 '13 at 16:40
  • 2
    It becomes easier to recognize the access path if you indent your code more nicely, or look at a [`print_r` rendition](http://array.include-once.org/?foreach=1&assoc=1&json=%5B%7B%22capital%22%3A%22Sacramento%22%2C%22joined_union%22%3A1850%2C%22population_rank%22%3A1%7D%2C%7B%22capital%22%3A%22Austin%22%2C%22joined_union%22%3A1845%2C%22population_rank%22%3A2%7D%2C%7B%22capital%22%3A%22Boston%22%2C%22joined_union%22%3A1788%2C%22population_rank%22%3A14%7D%5D%0D%0A). Indeed "main keys" or sometimes "top-level" array keys are common designations. – mario May 09 '13 at 16:41
  • 1
    While I answered below to help you understand arrays better - which is important ... In the long term, I agree with @ZombieHunter there - the more complex you get with your arrays, the more you probably want to go object oriented. – Wolfman Joe May 09 '13 at 16:44
  • 3
    @Zombie Objects are not inherently any cleaner. Multidimensional arrays are still perfectly useful. If you can and do define properly encapsulated custom classes for each data type you will indeed end up with more maintainable code, but that's not always applicable and isn't the question here. – deceze May 09 '13 at 16:46

3 Answers3

1

1: Multidimensional arrays are basically 'arrays of arrays'.

So if we look here:

array("0"=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1)

0 is the key, and the array is the value.

Then, inside the value, you have capital as a key, and Sacramento as a value.

2: For removing arrays: Delete an element from an array

3: State names for keys

Yes, you can change that 0, 1, 2 into state names. They become key-values instead of a numbered array. Which makes it much easier to remove exactly the one you want to remove.

Community
  • 1
  • 1
Wolfman Joe
  • 799
  • 1
  • 8
  • 23
1

Unlike other languages, arrays in PHP can use numeric or string keys. You choose. (This is not a well loved feature of PHP and other languages sneer!)

$states = array(
    "California"    => array(
        "capital"         => "Sacramento",
        "joined_union"    => 1850,
        "population_rank" => 1
    ),
    "Texas"         => array(
        "capital"         => "Austin",
        "joined_union"    => 1845,
        "population_rank" => 2
    ),
    "Massachusetts" => array(
        "capital"         => "Boston",
        "joined_union"    => 1788,
        "population_rank" => 14
    )
);

As for querying the structure you have, there are two ways
1) Looping

$joined1850_loop = array();
foreach( $states as $stateName => $stateData ) {
    if( $stateData['joined_union'] == 1850 ) {
        $joined1850_loop[$stateName] = $stateData;
    }
}
print_r( $joined1850_loop );
/*
Array
(
    [California] => Array
        (
            [capital] => Sacramento
            [joined_union] => 1850
            [population_rank] => 1
        )

)
*/

2) Using the array_filter function:

$joined1850 = array_filter(
    $states,
    function( $state ) {
        return $state['joined_union'] == 1850;
    }
);
print_r( $joined1850 );
/*
Array
(
    [California] => Array
        (
            [capital] => Sacramento
            [joined_union] => 1850
            [population_rank] => 1
        )

)
*/

-

$joined1800s = array_filter(
    $states,
    function ( $state ){
        return $state['joined_union'] >= 1800 && $state['joined_union'] < 1900;
    }
);
print_r( $joined1800s );
/*
Array
(
    [California] => Array
        (
            [capital] => Sacramento
            [joined_union] => 1850
            [population_rank] => 1
        )

    [Texas] => Array
        (
            [capital] => Austin
            [joined_union] => 1845
            [population_rank] => 2
        )

)
*/
meouw
  • 41,754
  • 10
  • 52
  • 69
  • 1
    I would disagree with "This is not a well loved feature of PHP" - PHP's "array" data-type is one of the language's most powerful features, and can be used in place of all sorts of dedicated types (lists, vectors, hashes, queues & stacks, sets, multisets, etc) – IMSoP May 09 '13 at 18:14
  • @IMSoP Which may or may not be a good thing; dedicated types can make things better, just as all strict type safety is usually good. I agree though that I have hardly ever heard anyone complain about PHP's array type. – deceze May 09 '13 at 18:47
  • @deceze Dedicated types are indeed useful, but you do rely on there being one available that meets your needs. Javascript, for instance, has no "ordered hash" type (objects can be used as hashes, but there is no requirement for the runtime to produce properties in any particular order when looping). I am aware that it is an opinion, but I find PHP's array type, and type system in general allows for some very handy algorithms - if used carefully. – IMSoP May 09 '13 at 18:53
  • Thanks @meouw! Also thanks to everyone for the excelent feedback and answers! Stack is awesome and I'm excited to learn more! Chose meouw because of the loop part. – Patty May 09 '13 at 21:07
1

Multidimensional arrays are simply arrays which have arrays as values. Simple or "scalar" types are types likes int, string and bool, they hold one value and one value only. Arrays are a compound type, meaning it's a thing that combines several other things together. An array can contain values of other types, including arrays.

The simplest visualization is probably this longhand:

$array = array('foo' => array('bar' => 'baz'));

$foo = $array['foo']; // $foo is now array('bar' => 'baz')

echo $foo['bar']; // outputs 'baz'

This is just shorthand for the same thing as above:

echo $array['foo']['bar'];

$array['foo'] gives you access to the value array('bar' => 'baz'), ['bar'] on that array gives you the value 'baz'. It doesn't matter whether you assign the intermediate value into a variable or continue directly.

The other way around, here's a demonstration of the concept that multidimensional arrays are just arrays in arrays:

$baz   = 'baz';
$bar   = array('bar' => $baz);
$array = array('foo' => $bar);

That's all there is to it.

You can call nested arrays in array "sub arrays", though there's no real definition and it's not really necessary to define this, since nested arrays aren't a special case of anything.

You may stumble upon explanations using the terms "two dimensional", "three dimensional" etc. arrays. Do not imagine this as tables and cubes, because it's not accurate and will make your head explode when it goes beyond three dimensions. This "dimensionality" simple refers to the depth of the array, i.e. how many arrays are nested within each other.

deceze
  • 510,633
  • 85
  • 743
  • 889