4

I am trying to build an sql query using an array and add a prefix.

E.g:

$columns = array('column1', 'column2');

"SELECT ". ltrim(implode(", media_", $columns), ', ') . " FROM media WHERE media_id = '{$id}'";

Outputs:

SELECT filename, media_image FROM media WHERE media_id = '3'

What I really want:

SELECT media_column1, media_column2 FROM media WHERE media_id = '3'

Question: How can I: 1. Prefix all items of the array with "media_" 2. Separate more than 1 item with a comma?

4 Answers 4

14

why not put "media_" to the front?:

$columns = array('column1', 'column2');
$selectColumns = 'media_' . implode(', media_', $columns);

"SELECT {$selectColumns} FROM media WHERE media_id = '{$id}'";

you can also use array_map:

$columns = array_map(function($column) {
    return 'media_' . $column;
}, $columns);

"SELECT " . implode(',', $columns) . " FROM media WHERE media_id = '{$id}'";
Sign up to request clarification or add additional context in comments.

2 Comments

Because implode(); takes 2 arguments, suffix (sort of) and array. If you concatenate an array with a string, PHP will automatically cast the array to a string, and implode will try and implode a string. T_T
@ZanderRootman Implode will actually returns string. Any function will not change its parameters property type because function is concatenated to string. In this case implode second parameter will always be an array. I've been using it for more than 2 years. It will only change property type if you directly concatenate string with an array.
0

[Edited]
Another way

$fields = array_reduce($columns, function ($result, $element) {
  $result = is_null($result) ? 'media_'.$element : $result.', media_'.$element;
  return $result;
});

"SELECT {$fields} FROM media WHERE media_id = '{$id}'";

Comments

0

Yet another way:

<?php

$id = 1;
$columns = array('column1', 'column2');
array_walk($columns,'add_prefix','media_');

function add_prefix(&$item, $key, $prefix) {
    $item = $prefix . $item;
}


$sql = "SELECT `" . implode('`,`', $columns) . "` FROM media WHERE media_id = '{$id}'";
echo "SQL:" . $sql . "\r\n";

Pick which one works best for you.

Comments

0

Here is a useful function, also to add suffixes

 <?php
    $arr=['media1','media2','media3','media4'];
    
    echo join_add(' ',$arr,'colum_','_more');
    #Output: colum_media1_more colum_media2_more .....
    
    function join_add($sep = '', $str = array(), $pref = '', $suff = '') {
       return $pref . join($suff . $sep . $pref, $arr) . $suff;
    }

?>

Demo: https://onlinephp.io/c/41aa0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.