Converting PHP Arrays with Key Values to String Statement

Why we may need this let understand this first. For example when I was writing a database class I was using a method like that.

$params = [
    'ORDER BY' => 'date DESC',
    'LIMIT' => '0, 10'
];
Database::select('messages', $params)

To use them easily i need to combine the array which has key value then convert them into the string. So mysql code should be like this;

SELECT * FROM messages ORDER BY date DESC LIMIT 0, 10

I did this in a easiest way

$params = [
    'ORDER BY' => 'date DESC',
    'GROUP BY' => 'date',
    'LIMIT' => '0, 15'
];
array_walk($params, function(&$i, $k){
    $i = "$k $i";
});
$sql = implode(' ', $params);
echo $sql; // Result: ORDER BY date DESC GROUP BY date LIMIT 0, 15

Instead of assigning one variable and using in foreach loop, we used array_walk() which is one of the array functions. And in anonym function we set our key to key-vaue. We combined the array by using implode()  and we got what we want

Comments

There are no comments, make the firs comment