rsabir
rsabir

Reputation: 736

Reference in element of the array another element of the same array

Is there a possibility to reference an element of an array in another element with the same array?

Let's say we want to make an array like this:

$a = array(
    'base_url' => 'https://rh.example.com',
    'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$this['base_url'],
);

Of course, it doesn't work because $this is intended for classes not for arrays. So is there an alternative?

Upvotes: 3

Views: 1328

Answers (5)

Faquarl
Faquarl

Reputation: 158

You can't do what you want with arrays because they are only data. But you can do this with an object:

$myCustomArray = new stdClass;
$myCustomArray->base_url = 'https://rh.example.com';
$myCustomArray->URL_SLO_OpenAM_OIC = function () { echo 'https://openam.example.com/openam/UI/Logout?goto='.$this->base_url; };

and then do : $myCustomArray->URL_SLO_OpenAM_OIC();

Upvotes: 1

Progrock
Progrock

Reputation: 7485

An alternative approach would be to substitute values after assignment, using tokens for simple cases.

<?php

function substitutor(array $array) {
    foreach ($array as $key => $value) {
        if(preg_match('/@(\w+)@/', $value, $match)) {
            $array[$key] = str_replace($match[0], $array[$match[1]], $value);
        } 
    };

    return $array;
}

$array = array(
    'foo' => 'bar',
    'baz' => 'some' . '@foo@'
);

var_dump($array);
$substituted = substitutor($array);
var_dump($substituted);

Output:

array(2) {
  ["foo"]=>
  string(3) "bar"
  ["baz"]=>
  string(9) "some@foo@"
}
array(2) {
  ["foo"]=>
  string(3) "bar"
  ["baz"]=>
  string(7) "somebar"
}

Upvotes: 0

Shan
Shan

Reputation: 31

You can not reference an array element to another element. Array dose not have such functionality. It will gives you an undefined variable error if you are doing this. Answer to your question, you can store the value to an another variable and use that variable while initializing an array.

$base_url = 'https://rh.example.com';
$a = array(
'base_url' => $base_url,
'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$base_url,);

Upvotes: 1

revo
revo

Reputation: 48711

No it's not possible that way. You can't reference to the same array within its context. But here is a work around:

$a = array(
    'base_url' => ($base_url = 'https://rh.example.com'),
    'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$base_url,
);

Upvotes: 9

Alexander Guz
Alexander Guz

Reputation: 1364

An alternative would be to add elements to array one by one.

$a['base_url'] = 'https://rh.example.com';
$a['URL_SLO_OpenAM_OIC'] = 'https://openam.example.com/openam/UI/Logout?goto='.$a['base_url'];

Upvotes: 2

Related Questions