tags:

views:

137

answers:

12
+2  Q: 

PHP foreach loop

I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:

if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }

I am then looping through the array and adding the rest of the SQL statement:

foreach ($val as $r){
    echo $r.'=1 AND ';
}   

This produces:

olderpeople=1 AND palcare=1 AND lookchild=1 AND

When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.

How I want it to complete:

olderpeople=1 AND palcare=1 AND lookchild=1
+10  A: 

Implode

In these situations you can use implode

It 'glues' an array together.

implode ( string $glue , array $pieces )

Example:

echo implode('=1 AND ', $val);
echo '=1';
Michael Robinson
You're missing the close quote on the last echo, and you're missing a space after `AND`.
Peter Ajtai
**Blushes** Thanks @Peter
Michael Robinson
Thanks Michael. Works as requested!
baswoni
Happy I could help :)
Michael Robinson
A: 

Try this :

$isFirst = true;
foreach ($val as $r){
    if(!$isFirst){
        echo ' AND ';
    }else{
        $isFirst = false;
    }
    echo $r.'=1';
}
Colin Hebert
+1  A: 

This is what implode() is for:

$result = array();
foreach ($val as $r){
    $result[] = "$r=1";
}
$result = implode($result, ' AND ');

Live Example

Peter Ajtai
+3  A: 

A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.

WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
Mark Byers
+1  A: 

use the implode function

$sql = implode("=1 AND ", $array)."=1";

and you wont have to use a for loop :)

pleasedontbelong
What about the very last item? `blah=1 AND orange`. (it won't get the necessary `=1`)
Peter Ajtai
oh yes yes =D thxs
pleasedontbelong
+1  A: 

Just don't print the AND for the last value of the foreach loop. Here is the code to use:

foreach ($val as $r){
    echo $r.'=1';

    if (next($val)) {
        echo ' AND ';
    }
}
Chetan
A: 

I would remove the last 4 characters of the string with:

$r = '';

foreach ($val as $r){
    $r.'=1 AND ';
}

$r = substr($r, 0, -4);
echo $r;

Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy

instigator
+1  A: 

Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them

implode(" AND ", $val);
sberry2A
A: 

I'd recommend holding the query in a variable before echo'ing it, then you can use the substring function substr() to remove the last extra bit.

$appender = ' AND ';
$where = '';
foreach ($val as $r){
    $where .= $r .'=1' . $appender;
}

$where = substr($where, strlen($where)-strlen($appender));

echo $where;
brianghig
A: 

If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.

I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:

$sqlwhere = "";
foreach ($val as $r){
   if($sqlwhere ==""){
      $sqlwhere = $r;
   }
   else {
      $sqlwhere .= " AND " . $sqlwhere;
   }
}
echo $sqlwhere;

I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.

Christa
A: 

Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:

$seperator = '';
$result = '';
foreach ($array as $value) {
    // .. Do stuff here
    $result .= $seperator . $value;
    $seperator = ' AND ';
}

The benefit is both brevity and flexibility without checking conditions all the time...

ircmaxell
A: 

Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.

$result = array();
$totalcount = count($val);
$currentCount = 0;

foreach ($val as $r){
  $currentCount ++;    
  if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}

}
Jason