UI Dev
UI Dev

Reputation: 699

Checking a string in an array fails

I have following PHP code

$selected_items = explode(',' , $vars['value']);

foreach($vars['options'] as $option) {
    $selected = ""; 
    if(in_array($option,$selected_items)){
        $selected = " selected = 'selected'";
      }
        echo "<option" . $selected . ">" . $option . "</option>";
}

  $selected_items:
  array
  0 => string 'Html' (length=4)
  1 => string ' Css' (length=4)
  2 => string ' HTML5' (length=6)
  3 => string ' CSS3' (length=5)
  4 => string ' Javascript' (length=11)

$vars['options']:
array
  0 => string 'Html' (length=4)
  1 => string 'Css' (length=3)
  2 => string 'HTML5' (length=5)
  3 => string 'CSS3' (length=4)
  4 => string 'Javascript' (length=10)
  5 => string 'Dhtml' (length=5)
  6 => string 'Actionscript' (length=12)
  7 => string 'Javafx' (length=6)
  8 => string 'Flex' (length=4)
  9 => string 'VisualBasic' (length=11)
  10 => string 'Ajax' (length=4)
  11 => string 'ASP.NET' (length=7)
  12 => string 'Java' (length=4)
  13 => string 'Php' (length=3)
  14 => string 'Perl' (length=4)
  15 => string 'Python' (length=6)
  16 => string 'J2ME' (length=4)
  17 => string 'VB.NET' (length=6)
  18 => string 'C#' (length=2)
  19 => string 'ASP' (length=3)
  20 => string 'JSP' (length=3)
  21 => string 'J2EE' (length=4)
  22 => string 'C++' (length=3)

In $selected_items have an array. So i have to check whether the value in $option is in $selected_items. But its working for first time. But second time the value is in array but the condition get false.

Any idea where is the problem ?

Upvotes: 0

Views: 73

Answers (2)

UI Dev
UI Dev

Reputation: 699

Just remove the space before string in array $selected_items.

Upvotes: 0

Muthukrishna C
Muthukrishna C

Reputation: 147

I thing it should work if that string present in array. If you have problem with above one you can try this:

$selected_items = explode(',' , $vars['value']);

foreach($vars['options'] as $option) {
    $selected = ""; 
    foreach($selected_items as $selecteditems){
    if($option == $selecteditems)){
        $selected = " selected = 'selected'";
      }}
        echo "<option" . $selected . ">" . $option . "</option>";
}

Upvotes: 1

Related Questions