简体   繁体   中英

Removing last word from FOREACH loop

I'm building a basic function, which builds out Mysql WHERE clauses based on how many are in the array.

$array = array('id' => '3', 'name' => 'roger'); 
$sql = "SELECT * FROM table WHERE ";

foreach ($array as $k => $v) {
    $sql .= $k . ' = ' . $v . ' AND ';
}

which will output

SELECT * FROM table WHERE id = 3 AND name = roger AND

However obviously I don't want that last AND, how do I go about removing it from the string?

Thanks

You could do

$sql = substr($sql, 0, -5);

But perhaps the more elegant solution is

$array = array('id' => '3', 'name' => 'roger'); 
$clauses = array();

foreach ($array as $k => $v)
    $clauses[] = $k . ' = ' . $v;

$sql = "SELECT * FROM table WHERE " . implode(' AND ', $clauses);
$array = array('id' => '3', 'name' => 'roger'); 
$sql = "SELECT * FROM table WHERE ";

foreach ($array as $k => $v) {
    $sql .= $k . ' = ' . $v . ' AND ';
}

$sql = substr(trim($sql), 0, -3);

I would do it this way:

$sql = "SELECT * FROM table WHERE 1=1 "; 
// add "AND x=y" for every pair of key, value pair in the array.    
foreach ($array as $k => $v) 
    $sql .= ' AND ' . $k . ' = ' . $v;

I've added a 1=1 to the where clause so that your query will be valid even if the array $array is empty .

$sql = trim($sql, ' AND ');

Reformulate the question. You're trying to put an AND after every clause except the last. It would be easier to put an AND before every clause except the first.


$first = true;
foreach ($array as $k => v) {
    if (!$first) $sql .= ' AND ';
    $first = false;
    sql .= $k . ' = ' . $v;
}

Maybe not the easiest way in this case (other people mentioned using substr). However, I've found it a good tool to remember in general for situations like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM