Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert dictionary to string (PHP)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading