0

In my SQL database I have a query that turns values in multiple rows into a single concatenated string.

id    |    image_filename    |    slides    |    languages    |    types
-------------------------------------------------------------------------
10    |    filename.jpg      |    55,4     |        1         |    TN,CQ

In PHP I am trying to check to see which slides this image is associated with. If it is associated, that checkbox will be checked.

$isChecked = (strpos($slide,"5") !== false) ? " checked=\"checked\"" : "";

The problem is that the statement above will return true because there is a 5 contained in there. What needs to happen is it will return false because 5 does not equal 55.

How can I create something in PHP to check the values before each comma, and see if it matches a certain string that I can specify.

Thanks!

Drew
  • 6,736
  • 17
  • 64
  • 96

3 Answers3

3

You should explode($slide) then convert to integers

$parts = explode(',', $slide);
if(intval($parts[0]) == 55) {
    // Do stuff
}
secretformula
  • 6,414
  • 3
  • 33
  • 56
  • Upvote for not missing the "before the comma" part of the post, although the integer conversion isn't necessarily necessary. :) – Sean Johnson Jun 30 '12 at 22:31
2

Compare the actual values conjoined by the comma!

$isChecked = in_array("5",explode(",",$slide))!=false?" checked=\"checked\"":"";

See explode.

Edit: Just noticed you only want to check the value BEFORE the comma only. This will actually be faster than creating an array from the string:

$isChecked = "5"==strstr($slide,',',true)?" checked=\"checked\"":"";

Assuming you have PHP 5.3+. See strstr

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
1

You should actually use the MySQL FIND_IN_SET() function to do this reliably at the RDBMS level. See this SO question, whose answer illustrates your goal.

Community
  • 1
  • 1
Lusitanian
  • 11,012
  • 1
  • 41
  • 38