user6247920
user6247920

Reputation:

Is it possible to get value from specified key in the same array?

I wonder if I can select any key inside my array, and set it as the value of another key. in order to be more clear (because my question may not clear enough), I try to do something like this:

$variable = array(
    'key'  => 'value',
    'key2' => $variable['key']
);

As you can see, it won't work (unless I do something like: $variable['key2'] = $variable['key'] out of the array, but this is not what i'm looking for and i'll use it only if I won't be able at all to do it inside the same array).

I searched for any solution but still haven't found one...

There is any way to do such thing inside the same array?

Thank you very much

Upvotes: 1

Views: 79

Answers (3)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

You must set $variable before

See

   $variable = new array();
   $variable['key'] = $variable->key2 = 'value';

Also

//create array
$variable = array(
        'key'  => 'value'
    );
    //then override
$variable = array(
        'key2'  => $variable['key'],
        'key'  => 'new_value'
    );

Upvotes: 0

HoldOffHunger
HoldOffHunger

Reputation: 20881

Think of it as the code doing what is in the parenthesis FIRST. Since $variable isn't set yet, you'll get an error on $variable['key'], since $variable isn't an array yet.

Upvotes: 0

Radosław Halicki
Radosław Halicki

Reputation: 149

This way you can`t do it, because this key does not exist yet.

Why to store two same variables in same array? Maybe show us what you are trying to do in bigger picture, so we can help you some way.

Upvotes: 1

Related Questions