How can I combine foreach..?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
birrd
Forum Newbie
Posts: 6
Joined: Mon Dec 01, 2008 10:47 am

How can I combine foreach..?

Post by birrd »

Hi,

I did my foreach (for an advanced search) separately because I had difficulties in dealing with my checkboxes result. Thankfully, it works now but... I'm not sure how I can combine the two foreach into just one, to produce a single foreach loop...


This is the first foreach...

Code: Select all

$sql = "SELECT * FROM movie WHERE publish=1 AND ";
 
$counter = 0; //checks whether an sql statement is a following or a first
 
foreach($_POST as $key => $value){
 
  if($key == "search"){
    if(empty($value)){
    $keyword = "";
    }else{
    $keyword = $value;
    }
  }else if($key == "searchby"){
    if(empty($keyword)){
    }else{
    $sql .= "$value LIKE '%$keyword%'";
    $counter = $counter + 1;
    }
  }else if($key == "Release_date"){
    if(empty($value)){
    }else{
    if($counter > 0){
    $sql .= "AND (Release_date >='$value')";
    $counter = $counter + 1;
    }else{
    $sql .= "(Release_date >='$value')";
    $counter = $counter + 1;
    }
    }
  }else if($key == "Release_date2"){
    if(empty($value)){
    }else{
    if($counter > 0){
    $sql .= " AND (Release_date >='$date1') AND (Release_date <='$value') Order by Release_date ASC";
    $counter = $counter + 1;
    }else{
    $sql .= "(Release_date >='$date1') AND (Release_date <='$value') Order by Release_date ASC";
    }
    }   
    }   
    }

This is another foreach...

Code: Select all

if(!empty($_POST["rating"]))  {
 
    $c=count($_POST["rating"])-1;
    $q=0;
    foreach($_POST["rating"] AS $keys)
    {
        $in_id.="$keys";
        if($q==$c)
        break;
        else
        $in_id.=",";
    
        $q++;
    }
    
    $sql="SELECT * FROM movie WHERE rating IN ($in_id) ORDER BY rating ASC";
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How can I combine foreach..?

Post by requinix »

Not giving us a whole lot of information here...

So in light of how I don't know what you're trying to accomplish ("combine two foreach loops into one" isn't the right answer) I'll mention that you can roll your own loop like

Code: Select all

$array1 = array(1, 2, 3); $array2 = array(2, 4, 6);
 
// reset: set the array back to the beginning
// each: get the current key and value from the array and advance to the next one
for (reset($array1), reset($array2); list($key1, $value1) = each($array1) and list($key2, $value2) = each($array2); ) {
    echo "$value1 + $value1 = $value2\n";
}
Post Reply