PHP add single quotes to comma separated list

前端 未结 7 1123
逝去的感伤
逝去的感伤 2021-02-05 05:55

When I implode my array I get a list that looks like this:

qwerty, QTPQ, FRQO

I need to add single quotes so it looks like:

\'         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 06:08

    Here is another way:

    $arr = ['qwerty', 'QTPQ', 'FRQO'];
    
    $str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));
    
    echo $str; //'qwerty', 'QTPQ', 'FRQO'
    

    sprintf() is a clean way of wrapping the single quotes around each item in the array

    array_map() executes this for each array item and returns the updated array

    implode() then turns the updated array with into a string using a comma as glue

提交回复
热议问题