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
2
  • 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. Commented Jan 11, 2023 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. Commented Jan 11, 2023 at 20:12

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

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
The question doesn't say anything about printing the value of that array element.
See stackoverflow.com/questions/27929875/… for how to get the value of the array element from the $args array.
I will ask the question carefully, this page solved my problem, thank you very much for your help

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.