Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a string variable that has multiple values in the following format:

123, xyz, abc

It may even have a single value only (in that case there wont be any comma after it)

How do I parse through these values in a for loop, going over each value at a time?

share|improve this question

2 Answers 2

up vote 2 down vote accepted
$input="123, xyz, abc"; 
foreach (explode(",",$input) as $value) { 
    var_dump(trim($value)); 
}
share|improve this answer
    
the code does not work when the variable has just a single value without any comma after it- what do I do in that case? (I ran your code and checked). –  Arvind Jun 15 '13 at 14:05
1  
It works fine here: $input="123"; foreach (explode(",",$input) as $value) { var_dump(trim($value)); } string(3) "123" –  faffaffaff Jun 15 '13 at 14:06
2  
sorry- my echo statement had a problem :( it works fine :) thanks a lot –  Arvind Jun 15 '13 at 14:11

Try to explode with comma ',' like

$your_arr = "123,xyz,....";
$my_arr = explode(",",$your_arr);
foreach($my_arr as $arr) {
      echo $arr;
      //Do the stuff HERE
}
share|improve this answer
    
Is it working....??? –  Gautam3164 Jun 15 '13 at 11:20
1  
it works fine :) thanks- but i can only accept one answer as the right one :( –  Arvind Jun 15 '13 at 14:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.