0

I need to update a specific key of an associative array thrue a function. Is it possible ?

IMPORTANT, in $PATH_TAB = &$TAB_cars['car_1']['blue']; $TAB_cars['car_1']['blue'] can be different : $TAB_cars['car_1']['type']['light'], etc.

$TAB_cars = [
        'car_1' => [
            'red' => '',
            'blue' => '',
            'type' => [
                   'light' => '',
                   'big' => ''
                      ]
                    ],
        'car_2' => [
            'green' => '',
            'brown' => ''
            ]
        ];


function UpdateArray($PATH_TAB_2) {
    $PATH_TAB_2 = 'TEST 2';
}


$PATH_TAB_1 = &$TAB_cars['car_1']['blue'];
UpdateArray($PATH_TAB_1);

print_r($TAB_cars);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Jean
  • 59
  • 1
  • 8
  • You need to either `return` in your function or have it pass-by-reference – Patrick Q Nov 26 '19 at 14:13
  • Well, try to do something like : `$newArray = UpdateArray($PATH_TAB);` with `function UpdateArray($array, $path_tab) { /* update the $path_tab in your $array */ return $array; }` – Mickaël Leger Nov 26 '19 at 14:15
  • 1
    I can't understand this sentence _IMPORTANT, in $PATH_TAB = &$TAB_cars['car_1']['blue']; $TAB_cars['car_1']['blue'] can be different : "deeper" or not._ – nice_dev Nov 26 '19 at 14:16
  • @vivek_23 I just updated the sentence. Is it clear now ? THX – Jean Nov 26 '19 at 14:26
  • 1
    `function UpdateArray(&$PATH_TAB_2)`, then this would work. Rather terrible coding though, if you’d asked me. So far from your question it is not clear, what advantage that would be supposed to have, over just going `$TAB_cars['car_1']['blue'] = 'TEST 2';` directly. – 04FS Nov 26 '19 at 14:32
  • I have a slight suspicion that what you are actually trying to ask, is similar to https://stackoverflow.com/questions/9628176/using-a-string-path-to-set-nested-array-data – 04FS Nov 26 '19 at 14:35
  • @Jean I'm sorry to say it's still unclear. – nice_dev Nov 26 '19 at 14:37
  • @04FS THX for the solution. And no, I already saw this solution before... THX again – Jean Nov 26 '19 at 14:40

1 Answers1

0

The answer is (THX to @04FS) :

$TAB_cars = [
        'car_1' => [
            'red' => '',
            'blue' => '',
            'type' => [
                   'light' => '',
                   'big' => ''
                      ]
                    ],
        'car_2' => [
            'green' => '',
            'brown' => ''
            ]
        ];





function UpdateArray(&$PATH_TAB_2) {
    $PATH_TAB_2 = 'TEST 2';
}

$PATH_TAB_1 = &$TAB_cars['car_1']['blue'];
UpdateArray($PATH_TAB_1);

print_r($TAB_cars);
Jean
  • 59
  • 1
  • 8