test
test

Reputation: 18198

PHP - Reference associative array inside same one

Is it possible to get the associate array inside the same associative array? For example:

<?php
$config = [
    'uri' => [
        'base_url' => $_SERVER['HTTP_HOST'], // example.com
        'protocol' => 'https://',
        'url' => $config['uri']['protocol'] . $config['uri']['base_url'] // output: https://example.com
    ]
];

Obviously, that's not going to work but you get the idea. I've been looking at the PHP docs but I cannot find a definitive answer.

Upvotes: 1

Views: 58

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94672

Not like you have done it, but you can do it in 2 steps like this

$config = [
    'uri' => [
        'base_url' => $_SERVER['HTTP_HOST'], // example.com
        'protocol' => 'https://'
    ]
];

$config['uri']['url'] = $config['uri']['protocol'] . $config['uri']['base_url'];

print_r($config);

Upvotes: 2

Scopey
Scopey

Reputation: 6319

Use an intermediate variable:

$base = $_SERVER['HTTP_HOST'];
$protocol = 'https://';
$config = [
    'uri' => [
        'base_url' => $base, // example.com
        'protocol' => $protocol,
        'url' => $protocol.$base,
    ]
];

There's no reason to be afraid to use intermediate variables.

Upvotes: 3

Related Questions