Referring to sister element inside array in php

I want to do something like the following (key3 is a 1 + 2 combination):

$a = array(
    'key1' => 5,
    'key2' => 10,
    'key3' => $a['key1']+$a['key2'] // want it to be 15
);

How can i do this? Do I need to access from outside the array and then combine them? Because it does not work!

Thanks in advance,

Maurice

+3
source share
3 answers

You cannot initialize it, because PHP has not finished and initialized the whole array, so it cannot use its other values ​​yet.

You will need to do this after initializing the first two elements:

$a = array(
    'key1' => 5,
    'key2' => 10
); // At this point, $a is ready for use

$a['key3'] = $a['key1'] + $a['key2']; // Or simply = array_sum($a);
+6
source

A solution suggesting updating the table after this is a good one, but you can also use variables for your data:

$var1 = 5;
$var2 = 10;

$a = array(
    'key1' => $var1,
    'key2' => $var2,
    'key3' => $var1 + $var2
);
+5
source

:

$a = array(
    'key1' => 5,
    'key2' => 10,
    'key3' => 0
);

$a['key3'] = $a['key1']+$a['key2'];

. , , , , .

+1

All Articles