Removing the last word from a FOREACH loop

I am creating a basic function that builds Mysql WHERE clauses based on how many of them 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 the latter And, how can I remove it from the string?

thanks

+4
source share
5 answers

You could do

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

But perhaps a more elegant solution -

 $array = array('id' => '3', 'name' => 'roger'); $clauses = array(); foreach ($array as $k => $v) $clauses[] = $k . ' = ' . $v; $sql = "SELECT * FROM table WHERE " . implode(' AND ', $clauses); 
+12
source
 $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); 
+2
source

I would do it like this:

 $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 added 1=1 to the where clause so that your request is valid even if the $array empty .

+1
source

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

0
source

Reformulate the question. You are trying to put AND after every sentence except the last one. It would be easier to put AND before each sentence except the first.

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

Perhaps not the easiest way in this case (other people mentioned using substr). Nevertheless, I found it a good tool for memorizing in general for such situations.

0
source

Source: https://habr.com/ru/post/1305188/


All Articles