0

I have a php form with one of the fields being a dropdown box that allows multi select, this field is set as a varchar and points to another table for its options, the options are 1 to 8.

I would like to run an if code after adding a record, i can do this if the value is a single value, ie if($value==1), but as this dropdown allows multi select, it is possible for the field to save as 1,2,4,6 or 2,3,4, i.e. any combination of 1 to 8, and separated by a comma.

So what I need to do is get something like if($value....contains 1) {then do something }

Any ideas please

JKG79
  • 3
  • 2
  • If your `$value` is a string, then you can use [string_contains](https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word) – tola May 23 '23 at 15:13
  • Also, I found it a bit difficult to fully understand your question - do you want the page to react to the user's choice in the dropdown box, that's in that same page? – tola May 23 '23 at 15:15
  • "his field is set as a varchar" - what does that mean? Neither HTML nor PHP use varchars. Also, if that dropdown box allows multiple selections, it should always submit an array. A common ` – Nico Haase May 25 '23 at 13:43

2 Answers2

0

You can use explode method

Then you can use foreach loop

Example code will look like

$arrayWithValues = explode($value); 

foreach($arrayWithValues as $selectedOption ) {
  if($selectedOption ==1) {
     // Do smth
    }
}
  • This feels too much, when he can simply do `string_contains` – tola May 23 '23 at 15:26
  • Agree, this will work better IMHO if he wants to check for every condition, then there is one transformation and check for every value inside of this loop (more convenient for me) – Andrii Antoniuk May 23 '23 at 15:35
  • Also, if in some time number of options will increase to 10, will string_contains check for a char "1" (so 10 actually includes 1), or will it recognise it? – Andrii Antoniuk May 23 '23 at 15:37
  • Maybe `in_array` instead of loop. – AbraCadaver May 23 '23 at 20:08
  • Sure, I believe the in_array method under the hood just uses what I had written, except it returns true/false when the option is found. So, it depends on what @jkg needs – Andrii Antoniuk May 24 '23 at 17:41
0

the problem with string_contains is that if value contains a number 15, it would true the condition as it does contain 1 in 15...

<?php
    $value = explode(",", $value);
    //seperate the value string by a coma and create array
    
    if(gettype(array_search(1, $value)) == 'integer'){
    
    //search the array for '1', if it has it/ returns a number
    //do something
    
    
    }
     ?>