I need to write a function that converts a dictionary (array) ['a' => 1, 'b' => 2] to a string '[a => 1, b => 2]'.
I am trying to iterate over the array and just build a string from its items:
function dictToString(array $dict): string {
foreach($dict as $key => $value) {
echo $key . " => " . $value . ", ";
}
return "";
}
However, I’m not sure how to perform it well. I am getting such output: a => 1, b => 2,. Don’t know how to include brackets and get rid of the redundant comma.
Also not sure if this is even a good approach, maybe there’s a better way.
>Solution :
You can use something like this
function dictToString(array $dict): string {
$str = '[';
foreach($dict as $key => $value) {
$str .= $key . " => " . $value . ", ";
}
$str = rtrim($str, ", ");
$str .= ']';
return $str;
}
echo dictToString(['a' => 1, 'b' => 2]);
rtrim() remove the comma from the last iteration