Generate Array from a comma-separated list - PHP

前端 未结 3 1388
[愿得一人]
[愿得一人] 2020-12-19 00:23

I have a variable defined like so: $var = \"1, 2, 3\"; & I have an array: $thePostIdArray = array(1, 2, 3);

The Array above wo

相关标签:
3条回答
  • 2020-12-19 00:48

    Check out explode: $thePostIdArray = explode(', ', $var);

    0 讨论(0)
  • 2020-12-19 01:01

    For developer who wants result with and in the end can use the following code:

    $titleString = array('apple', 'banana', 'pear', 'grape');
    $totalTitles = count($titleString);
    if($totalTitles>1)
    {
        $titleString = implode(', ' , array_slice($titleString,0,$totalTitles-1)) . ' and ' . end($titleString);
    }
    else
    {
        $titleString = implode(', ' , $titleString);
    }
    
    echo $titleString; // apple, banana, pear and grape
    
    0 讨论(0)
  • 2020-12-19 01:07

    use explode function. this will solve your problem. structure of explode is like this

    array explode ( string $delimiter , string $string [, int $limit ] )
    

    now $delimiter is the boundary string, string $string is the input string. for limit:

    If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

    If the limit parameter is negative, all components except the last -limit are returned.

    If the limit parameter is zero, then this is treated as 1.

    visit the following link. you can learn best from that link of php.net

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