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.
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.
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.
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.
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.
Check out explode
: $thePostIdArray = explode(', ', $var);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With