Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Array from a comma-separated list - PHP

Tags:

arrays

string

php

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

The Array above works great when looping through it but when I try to use the $var in place of the comma-separated list, problems occur.

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

Every attempt so far hasn't worked :'(

Is this even possible, or is there an easier workaround?

Thank you for any pointers.

like image 517
michaelmcgurk Avatar asked May 31 '12 13:05

michaelmcgurk


People also ask

How can I convert a comma separated string to an array in PHP?

Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter.

How do you create an array with comma separated strings?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you store comma separated values in an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you add a comma to an array?

String with Just Commas When you want just the comma character ( , ) to appear as the separator between items in the list, use . join(",") to convert the array to a string.


2 Answers

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

like image 139
janmoesen Avatar answered Sep 30 '22 17:09

janmoesen


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

like image 26
Subail Sunny Avatar answered Sep 30 '22 18:09

Subail Sunny