...

View Full Version : How can I use a FOREACH conditionally ??



mOrloff
11-20-2010, 04:59 AM
I have a table of employees.
Under normal circumstances I loop through the whole array and gather data for all employees, however, if an employee is specified via $_GET, then I want to limit the scope to that single emp.

Here's a simplified example:


$empArray=array(1=>"Bob",2=>"Sally", 3=>"Dick", 4=>"Harry");

if(empty($_GET['empId'])){ // if NO emp is specified...
foreach($empArray as $empId=>$name){ //...go into a loop
}else{ // if an emp IS specified...
$empID=;$_GET['empId'] //...grab it
}
echo "ID: $empId <br/>";
echo "Name: $name <br/>";

if(empty($_GET['empId'])){ // if NO emp is specified..
} //...close the FOREACH() loop
}


I am getting an error on the }else{ line.
How can this be done??
How can I use the foreach() only if certain criteria are met??

Thanks-a-bunch,
~ Mo

MattF
11-20-2010, 05:12 AM
You can't start and finish within different conditionals like that.



$empArray=array(1=>"Bob",2=>"Sally", 3=>"Dick", 4=>"Harry");

if (empty($_GET['empId']))
{
foreach($empArray as $empId=>$name)
{
echo "ID: $empId <br/>";
echo "Name: $name <br/>";
}
}
else
{
$empID=$_GET['empId'];
echo "ID: $empId <br/>";
echo "Name: $name <br/>";
}

mOrloff
11-20-2010, 05:19 AM
Aww man!!!
I've got about 150 lines of code which are now going to have to be duplicated.

That would have been a SLICK way to save some unnecessary redundancy.
Thanks.
~ Mo

MattF
11-20-2010, 05:23 AM
I've got about 150 lines of code which are now going to have to be duplicated.

Why? That's what functions are for.

mOrloff
11-22-2010, 02:40 PM
Why? That's what functions are for.

Very good point. Thank you.

As an aside, I did figure out a way to make it work.
Simply, if $_GET['empId'] was passed, drop all other emps from the $empsArray array. Therefor the foreach() would only have one record to do its thing for.

Thank you again.
~ Mo



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum