-2

I am creating a festival webapp and we have two different sites. A vehicle can come to 'north', 'south', or 'both'.

The MySQL table stores a comma separated list with values of either '1', '2', or '1,2'.

Basically, I need the variable $site to be; North South or Both

I've tried the below (and other lsot iterations) but can't get the desired output

$a = array($r['site']);

if (in_array(array('1', '2'), $a)) {
  $this->site = 'both';
}

if (in_array('1', $a)) {
  $this->site = 'north';
}

if (in_array('2', $a)) {
  $this->site = 'south';
}

Desired result is for $this->site to equal;

1 = North

2 = South

1,2 = Both

Brad Sullivan
  • 97
  • 1
  • 1
  • 8
  • 2
    why don't you use the name-giving strings instead in your database? – Franz Gleichmann Apr 10 '19 at 15:12
  • Have a read of https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Nigel Ren Apr 10 '19 at 15:16
  • You can use array_search() function to check weather value is present inside array or not. – Vitthal Apr 10 '19 at 15:18
  • 1
    @Franz Gleichmann -- i've jumped into a project to sort someone elses half-baked idea out. so this is my only solution for today. that's how I'd do it.. and how other modules i've created from scratch work – Brad Sullivan Apr 10 '19 at 15:35

1 Answers1

0

Wrapping a string in array() doesn't split it into an array. You could use explode() on it, or something simple:

$map = array(1 => 'north', 2 => 'south', '1,2' => 'both');
$this->site = $map[$r['site']];

However, it's not a good idea to store comma separated lists in a single database column. This gets messy, suppose you also have East and West or North 1 and North 2 etc.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Hey @AbraCadaver, thanks so much for the tip here. This has got me going with todays rush, and YES! I have other sections of the app which stores values in a separate column in a separate table (many/multi relationships as you described) but I had to rush this out to create a list by a deadline, so your solution helps today, and I can reapproach it shortly – Brad Sullivan Apr 10 '19 at 15:33