1

When I use values fetched from a comma-separated list in a db to form an array, I am having trouble getting them to behave the same way as hard coded arrays.

I believe this is due to the syntax within the array when it's created from db values, specifically that values aren't being encased in quotes, but I haven't successfully figured out how to insert them into the array itself.

For example, when I run the snippet which I've posted at the bottom of the page using:

Array (hard coded):

$colors_loveArray = array('Black','Charcoal','Light_Gray','White','Royal_Blue','Dodger_Blue','Red');

The output is:

Array = 'Black','Charcoal','Light_Gray','White','Royal_Blue','Dodger_Blue','Red',

Matches: Black

Array formed with values fetched from db (comma-separated list):

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {         
    $colors_loveArray[] = $row['colors_love'];
}  

The output is:

Array = 'Black,Charcoal,Light_Gray,White,Royal_Blue,Dodger_Blue,Red',

No Match Black


Code which is being run:

$Color='Black';

echo "$colors_loveArray = ";
foreach ($colors_loveArray as $value) {
    echo "'".$value."',";
}

if (in_array($Color, $colors_loveArray)) {
    echo "Matches: ", $Color;
}
Else {
    echo "No Match ", $Color;
}
Community
  • 1
  • 1
Chaya Cooper
  • 2,410
  • 1
  • 33
  • 65
  • Thank you for all the awesome help :-) Since I could only accept one answer, I accepted @Benpix because it was so straightforward and easy to understand, and upvoted Tengiz & showdev's answers :-D – Chaya Cooper Sep 19 '14 at 03:35

3 Answers3

2

You need to explode your comma-delimited string.

explode(",", $row['colors_love']);

Which will give you the same as your hard-coded array.

bnx
  • 417
  • 5
  • 11
  • Thank you for giving me such a perfect answer - it's not only the rare one that's super straightforward and easy to understand, it also answered my question and helped me learn something new :-D I'm now curious to know why I had to do an explode (and what it's actually doing - is it just inserting quotes or does it actually convert it into something, etc.) – Chaya Cooper Sep 19 '14 at 03:46
1

Obviously, your variable $colors_loveArray contains the following:

array(1) "Black,Charcoal,Light_Gray,White,Royal_Blue,Dodger_Blue,Red"

and you might want to break is to an array using

$arr = explode(',', $colors_loveArray);

also, if your CSV file is multiline, you need to separate each line first:

$lines = explode("\r\n", $colors_loveArray); // could be just \r or \n or \r\n as a line separator
Tengiz
  • 1,504
  • 12
  • 12
0

The hard coded array is an array of 7 values that your code display as as CSV.

The DB array seems to be an array of 1 CSV value.

"Black" doesn't match the only value of this array, which is "Black,Charcoal,Light_Gray,White,Royal_Blue,Dodger_Blue,Red".

user327961
  • 2,188
  • 3
  • 18
  • 19