0

I am trying to turn a multidimensional array into a patterned string with this array_map function:

function array_to_string($array) {
    return implode("&",array_map(function($a){return implode("~",$a);},$array));
}
$arr = array("hello",array("blue","red"),array("one","three","twenty"),"random");
array_to_string($arr);

Between each array element "&" and between each sub-array element (if it is an array) "~"

Should Output: hello&blue~red&one~three~twenty&random

However this outputs: Warning: implode(): Invalid arguments passed (2) I tried changing the function within the array_map to detect whether the multi-array's value is_array but from my outputs, I don't think that is possible? So essentially, I guess the real question is how can I place a test on the array_map function to see whether or not it is_array

0

1 Answer 1

2

Since $a can be an array or a string, you should check it in your callback function:

function array_to_string($array) {
    return implode("&",
               array_map(function($a) {
                   return is_array($a) ? implode("~",$a) : $a;
               }, $array)
           );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.