Generate an array from a comma separated list - PHP

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

The array above works fine when passing through it, but when I try to use $ var instead of a comma separated list, problems arise.

So (ideal world) it could be $ thePostIdArray = array ($ var); which will be the same as $ thePostIdArray = array (1, 2, 3); .

Each attempt has not yet worked: '(

Is this possible, or is there an easier way around this?

Thanks for any pointers.

+6
source share
3 answers

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

+40
source

use the break function. this will solve your problem. blast structure is like this

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

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

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

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

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

follow the link below. you can learn best php.net link

+2
source

For a developer who wants to get the result with and , at the end, you 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 
+2
source

Source: https://habr.com/ru/post/917106/


All Articles