Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP iterating through a simple comma separated list

Tags:

php

I have a string which can be

$string = "value.";

OR

$string = "value1, value2.";

I want to iterate through this string getting each item which are -> value (in first example) and -> value1 AND value2 in the second (without the comma or the dot in the end).

I was thinking of;

  1. Replace the dot in the end.
  2. Check if there is any comma.
  3. If there is comma, split-explode using ", " and iterate through.
  4. If not, only one item so just use it.

Is this the right way of doing it?

I am new to PHP and trying to learn best practices and best ways of solving the issues.

Thank you.

like image 225
Phil Avatar asked May 31 '12 18:05

Phil


1 Answers

You're absolutely right, you could do it like this:

$string = 'foo, bar, baz.';
$string = preg_replace('/\.$/', '', $string); //Remove dot at end if exists
$array = explode(', ', $string); //split string into array seperated by ', '
foreach($array as $value) //loop over values
{
    echo $value . PHP_EOL; //print value
}
like image 198
Tyilo Avatar answered Nov 13 '22 14:11

Tyilo