anditpainsme
anditpainsme

Reputation: 649

Defining indexes+elements in an associative array

Why does the following code:

if (isset($_GET['trainType']) && isset($_GET['onTime']) && isset($_GET['gotSeat'])) {
    $train[0]['trainType'] = $_GET['trainType'];
    $train[0]['trainType']['onTime'] = $_GET['onTime'];
    $train[0]['trainType']['gotSeat'] = $_GET['gotSeat'];   
    echo '<pre>';
    print_r($train);
    echo '</pre>';
}

Return the following array:

Array
(
    [0] => Array
        (
            [trainType] => tLine
        )

)

I had initially assumed it would return something more resembling to this:

Array
(
    [0] => Array
        (
            [trainType] => 'passenger'
            Array =>
                (
                    [onTime] => true
                    [gotSeat] => true
                )

        )

)

Any guidance on what I should do to achieve what I am trying to do? I am hoping that my code makes what I am trying to do obvious.

Upvotes: 1

Views: 88

Answers (2)

Stefan
Stefan

Reputation: 3900

You are implicitly setting (or needing) a key = 0 for

array (
  "onTime" => true,
  "gotSeat" => true
)

So you must instead just do this:

if (isset($_GET['trainType']) && isset($_GET['onTime']) && isset($_GET['gotSeat'])) {
    $train[0]['trainType'] = $_GET['trainType'];
    $train[0][0]['onTime'] = $_GET['onTime'];
    $train[0][0]['gotSeat'] = $_GET['gotSeat'];
    echo '<pre>';
    print_r($train);
    echo '</pre>';
}

Note that all I did was to change the incorrect $train[0]['trainType']['onTime'] to $train[0][0]['trainType'] in your code, and similarly for gotSeat.

Or you can define a new key, maybe like this: $train[0]['booking']['onTime'] = ...

Upvotes: 0

noetix
noetix

Reputation: 4923

This line will set trainType to a string value:

$train[0]['trainType'] = 'hello';

Then these lines will actually be used for character substitution, with a slight twist:

$train[0]['trainType']['onTime'] = 'foo';
$train[0]['trainType']['gotSeat'] = 'bar';

Both onTime and gotSeat will result in 0 (because you're working with a string) and will replace the first character with f then b.

Therefore print_r($train) returns:

(
    [0] => Array
        (
            [trainType] => bello
        )

)

Here is how I would format this data:

// define our list of trains
$train = array();

// create a new train
$new = new stdClass;
$new->type = 'a';
$new->onTime = 'b';
$new->gotSeat = 'c';

// add the new train to our list
$train[] = $new;

The result of print_r($trains):

Array
(
    [0] => stdClass Object
        (
            [type] => a
            [onTime] => b
            [gotSeat] => c
        )

)

Accessing this data:

echo $trains[0]->type; // returns 'a'
echo $trains[0]->onTime; // returns 'b'
echo $trains[0]->gotSeat; // returns 'c'

Upvotes: 1

Related Questions