14

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.

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

3 Answers3

63

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

janmoesen
  • 7,910
  • 1
  • 23
  • 19
5

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

Subail Sunny
  • 287
  • 4
  • 11
2

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
Waqar Alamgir
  • 9,828
  • 4
  • 30
  • 36