How to: concatenate a php array generated from a mysql query?

1059 views php

I am working on a player name generator using MYSQL/PHP. How do I select the values of a one column (not including primary key) table into a one-dimensional array and then concatenate the values of the array?

example table 'syllableInitials':


php code

$syllable = array("","","");

$sql = "SELECT characters FROM syllableInitials";
$result = $conn->query($sql);

$syllableInitials = array();

while ($initial = mysqli_fetch_row($result)) {
    $syllableInitials[] = $initial;
$syllableMedials = array("a", "o", "i");
$syllableFinals = array("m","s","d");

$syllable[0] = $syllableInitials[0] . $syllableMedials[2] . $syllableFinals[0];

echo "Syllable is: <b>" . $syllable[0] . "</b>";

Output I get is:

Notice: Array to string conversion in line... Syllable is: Arrayim

Obviously, my intended output for the above example code would be "tim" not "Arrayim".

A print_r for the syllableInitials array generates this...

Array (
     [0] => Array ( [0] => t )
     [1] => Array ( [0] => d ) 
    [2] => Array ( [0] => ch )

So it looks like somehow I am inadvertently nesting the array or causing it to be two-dimensional! My coding is real rusty... thanks in advance!

answered question

1 Answer


Since $initial is an array and has one element you can do:

$syllableInitials[] = $initial[0];

But a better solution would be to use PDO with its PDOStatement::fetchColumn function.

posted this

Have an answer?


Please login first before posting an answer.