0

I want to get dynamic data from multidimensional array in php, but it gives me error: Array to string conversion

function alt(){
    $arr = [
        'alt'=>'website title',
        'alert' => [
            'get'=>[
                'login'=>'succes loging',
                'register'=>'succes register'
            ]
        ]
    ];

    $value = func_get_args();
    $revert = null;
    for ($i=1; $i < count($value); $i++) { 
        $revert.= '['.$value[$i].']';
    }
    return $arr[$value[0]].$revert;
}

echo alt('alert','get','login');

the output i wanted

$arr['alert']['get']['login']; //succes loging
Barmar
  • 741,623
  • 53
  • 500
  • 612
Muhammed
  • 27
  • 7
  • When you do concatenation, the operands have to be converted to strings. Converting an array to a string results in the warning you got, and the value is the literal string `Array`. – Barmar Jan 11 '23 at 20:10
  • 1
    It's confusing what you're trying to do here. You want the output to be that source code string? Or you want the output to be the value of the thing that's in that array position? Why not just `echo $arr['alert']['get']['login'];` -- you're making this much more complicated than it needs to be. – Alex Howansky Jan 11 '23 at 20:12

1 Answers1

1

No, it's not possible to concatenate an array and a string. The array will be converted to the string Array before concatenating it, not the variable that points to the array. To get the result you want, you don't even need the $arr array.

fuction alt(...$args) {
    $revert = '$arr';
    foreach ($args as $arg) {
        $revert .= "[$arg]";
    }
    return $revert;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thank you, but is it possible to run the output? Returns the output as a string, does not print the array result to the screen, I'm just learning new things – Muhammed Jan 11 '23 at 20:54
  • The question doesn't say anything about printing the value of that array element. – Barmar Jan 11 '23 at 20:56
  • 1
    See https://stackoverflow.com/questions/27929875/how-to-access-and-manipulate-multi-dimensional-array-by-key-names-path for how to get the value of the array element from the `$args` array. – Barmar Jan 11 '23 at 20:57
  • I will ask the question carefully, this page solved my problem, thank you very much for your help – Muhammed Jan 11 '23 at 21:14