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

asked Sep 7, 2012 at 4:14
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)
 );
}
answered Sep 7, 2012 at 4:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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