Page 1 of 1

foreach loop question

Posted: Thu May 20, 2010 3:30 am
by korki696
Hey all,
I am fairly new to php and programming in general and I am having problem with this. What I have is a multiple selection box. I also have 2 arrays and I need to compare them to see if they match. If any of the items match I need that item to be selected if it doesn't match I don't want it to be selected. Here is what I have but isn't working. The info is take from a mysql database.

Code: Select all

<?php 
$sel_projects = explode(',',$user->project); 
?>
		
<label style="font-weight:bold" for="project"><?php echo $this->lang->line('user_register_begin_18')?></label>
	<select multiple name="project[]" id="project_sel" onchange="">
	<?php
	foreach($projects->result() as $project)
	{
		foreach($sel_projects as $sel_project)
			{
				if ($sel_project == $project->name){
					echo "<option selected='selected' value='$project->name'>$project->name</option>";
				}
				else
				{
					echo"'<option value='$project->name'>$project->name</option>";
				}
			}
	}
	?>
</select><br /><br />
The output I get for that is:

Item1*
Item1
Item2
Item2*
Item3
Item3

Output I want:
Item1*
Item2*
Item3

(stars mean selected)

Thanks in advance

-Korki

Re: foreach loop question

Posted: Thu May 20, 2010 12:57 pm
by Chalks

Code: Select all

<?php
        foreach($projects->result() as $project)
        {
                $flag = true;
                foreach($sel_projects as $sel_project)
                        {
                                if ($sel_project == $project->name){
                                        echo "<option selected='selected' value='$project->name'>$project->name</option>";
                                        $flag = false;
                                }
                        }
                if($flag)
                        {
                                echo"'<option value='$project->name'>$project->name</option>";
                        }
        }
?>
You were printing every single value in $sel_projects for each item in $projects->result(). There is probably a more elegant way to handle this, but the flag works just fine.

Re: foreach loop question

Posted: Thu May 20, 2010 1:14 pm
by AbraCadaver
You can simplify it by not looping through the selected array (not tested):

Code: Select all

foreach($projects->result() as $project) {
	$selected = '';

	if(in_array($project->name, $sel_projects)) {
		$selected = "selected='selected'";
	}
	echo "<option $selected value='$project->name'>$project->name</option>";	
}

Re: foreach loop question

Posted: Thu May 20, 2010 1:33 pm
by Chalks
see, that's what I was too lazy to look up. Thanks, AbraCadaver. :D

Re: foreach loop question

Posted: Thu May 20, 2010 2:29 pm
by jaiswarvipin
thanks it help sme too