Home > Back-end >  Is it possible to concatenate an array and a string in php
Is it possible to concatenate an array and a string in php

Time:01-12

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

CodePudding user response:

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;
}
  •  Tags:  
  • php
  • Related