2

I'm a little stuck on trying to figure this one out, I think I understand the principles but just a little lost on the execution. Say we have:

$string = "Blue, Red, Yellow";

Which is a string read in from a DB (it includes the commas). Basically what I'm trying to do break these words apart and store them separately in an array (easier to work with). Will something like this work:

$string_parts = explode(",",$string);

Is it as easy as this, or is there a better way?

1
  • It's as easy as that. Do a print_r( $string_parts ); to see the results. Commented Aug 17, 2011 at 17:27

3 Answers 3

6

If you don't want to have spaces in the resulting array, add a space to the separator:

$string_parts = explode(", ", $string);

Note that this database design violates the First Normal Form.

Sign up to request clarification or add additional context in comments.

Comments

1

If it works, then it's as easy as that.

Comments

1

I'd agree with

$string_parts = explode(",",$string);

Afterwards, I would go through each element and trim off whitespace.

for($i = 0; $i < sizeof($string_parts); $i++)
    $string_parts[$i] = trim($string_parts[$i];

EDIT: Instead of going through a for-loop and trimming off whitespace, I'd suggest

$string = str_replace(" ", "", $string);

then exploding the string.

5 Comments

Better to add the space in the separator as phihag said.
I'd agree with that if the assumption is that the DB string parts will always be separated by a comma and a space. Mine would take longer to execute in that regard. However, mine will work if there is not always whitespace after a comma ("Blue, Green,Red").
In that case it might be better to use regex split with an optional whitespace character
Actually, probably even better would be to str_replace whitespace, then exploding.
Yea, the string will always contain commas. I appreciate the feedback guys, should be good to go.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.