1

I'm working on config file which contain huge array, instead of assigning same value again and can I reuse which is already assigned to other index(or key) in the time of creating array? and here is my code

<?php

return [

   //array
   //array
   //array

   'ar' => [
       'mainDirectory' => 'http://example.com/main/',

       'subDirectory'  =>  'http://example.com/main/sub/',

       // instead of using above can't I reuse which is already exist something like below
       // 'subDirectory'  =>  [ar.mainDirectory].'sub/'
    ]

   //array
   //array
   //array
];
?>

I know we can access array & its index's after it is created and just for curiosity is there any way we can access it in the time of creating array itself?

Thank you

1

2 Answers 2

1

YES, you can do that here is the code

<?php
    return [
        'ar' => [
            'mainDirectory' => $ref = 'http://example.com/main/',
            'subDirectory'  => $ref.'sub/',
        ]
    ];
?>

and worked example is below

<?php

function arrayRef(){
    return [
        'ar' => [
           'mainDirectory' => $ref = 'http://example.com/main/',
           'subDirectory'  =>  $ref.'sub/',
        ]
    ];
}

print_r(arrayRef());

?>

and output

Array
(
    [ar] => Array
        (
            [mainDirectory] => http://example.com/main/
            [subDirectory] => http://example.com/main/sub/
        )

)
Sign up to request clarification or add additional context in comments.

Comments

0

I don't think we can do like that. If you need to access some common values then why not tried with constant and then used that in all required places in your array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.