Search code examples
phparraysdynamic-arrays

Array Access "this" value


Is there a way in a PHP array to access an internal value? Much like a this in other languages.

I can't think of how that would work or if it is at all possible, but if you consider this layout:

$x = [
    "value1" => 1,
    "value2" => THIS.value1 + 1
]

Replace THIS with the right process to get the previous value. This is how the array would be laid out as well. This is also at the initialization level.


Solution

  • $x (most likely) does not (yet) exist whilst that command is executed. Therefore referencing it does not really make sense...

    In short: this is not possible and for good reasons.


    If the array does exist before, then this is possible obviously:

    $x = [
        "value1" => 1
    ];
    
    $x = [
        "value1" => 1,
        "value2" => $x['value1'] + 1
    ]
    

    but I doubt this is what you are looking for :-)