PHP add single quotes to comma separated list

前端 未结 7 1120
逝去的感伤
逝去的感伤 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

    0 讨论(0)
  • 2021-02-05 06:13

    Use ' before and after implode()

    $temp = array("abc","xyz");
    
    $result = "'" . implode ( "', '", $temp ) . "'";
    
    echo $result; // 'abc', 'xyz'
    
    0 讨论(0)
  • 2021-02-05 06:13

    It can also be as short as this:

    sprintf("'%s'", implode("', '", $array))
    
    0 讨论(0)
  • 2021-02-05 06:26
        $ids = array();
        foreach ($file as $newaarr) {
            array_push($ids, $newaarr['Identifiant']);
    
        }
       $ids =array_unique($ids);
        //$idAll=implode(',',$ids);
    
         $idAll = "'" . implode ( "', '", $ids ) . "'";
    
    0 讨论(0)
  • 2021-02-05 06:28
    function implode_string($data, $str_starter = "'", $str_ender = "'", $str_seperator = ",") {
        if (isset($data) && $data) {
            if (is_array($data)) {
                foreach ($data as $value) {
                    $str[] = $str_starter . addslashes($value) . $str_ender . $str_seperator;
                }
                return (isset($str) && $str) ? implode($str_seperator, $str) :  null;
            }
            return $str_starter . $data . $str_ender;
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:33

    You can set the glue to ', ' and then wrap the result in '

    $res = "'" . implode ( "', '", $array ) . "'";
    

    http://codepad.org/bkTHfkfx

    0 讨论(0)
提交回复
热议问题