0

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?

2 Answers 2

2
$input="123, xyz, abc"; 
foreach (explode(",",$input) as $value) { 
    var_dump(trim($value)); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

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).
It works fine here: $input="123"; foreach (explode(",",$input) as $value) { var_dump(trim($value)); } string(3) "123"
sorry- my echo statement had a problem :( it works fine :) thanks a lot
2

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
}

1 Comment

it works fine :) thanks- but i can only accept one answer as the right one :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.