Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last word from FOREACH loop

Tags:

foreach

php

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

like image 755
Stoosh Avatar asked Dec 08 '22 03:12

Stoosh


1 Answers

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);
like image 98
Casey Chu Avatar answered Dec 29 '22 01:12

Casey Chu