views:

61

answers:

6

Hello everyone,

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:

$finalarray = $results_array + string;

A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.

$query = "SELECT * FROM table";
$showresult = mysql_query($query);

while($results_array = mysql_fetch_assoc($showresult))
{
  $finalarray =  $finalarray + $results_array["column"];
}

Edit:

Currently using this code (still not working):

    $query = “SELECT * FROM table”;
$showresult = mysql_query($query);

while($results_array = mysql_fetch_assoc($showresult))
{
  $finalarray[] = $results_array["name"];
}

echo $finalarray;

The problem is that it just says "Array"

Thanks,

Kevin

+2  A: 

Use the [] notation. + is for unioning two arrays.

$array = array('foo');

$array[] = 'bar'.

// $array == array('foo', 'bar')
deceze
If I add the two brackets, my array is a list of strings that say "Array" over and over again.
Kevin
@Kevin Could you show us the actual code with which this is happening?
deceze
Edited in the question.
Kevin
+1  A: 

Take a look at this

$query = "SELECT * FROM table";
$showresult = mysql_query($query);

while($results_array = mysql_fetch_assoc($showresult))
{
    $finalarray[] = $results_array["column"];
}

// Add X to the end of the array
$finalarray[] = "X";
jakenoble
+2  A: 

You can use the function array_push or [] notation:

array_push($array, 'hi');

$array[] = 'hi';
Jacob Relkin
+4  A: 

Answer to your edited question:

You cannot use just a single echo to print the entire array contents. Instead

Use

var_dump($finalarray);

or

print_r($finalarray);

to print the array contents..

codaddict
A: 

Codaddict is correct. You are looking to output the last element that was added to the array.

echo end($final_array);

That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...

$finalarray[] = $results_array["name"];

The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...

echo $final_array[count($final_array) - 1];
LynxStar
A: 
echo implode($finalarray);

Or with a custom join "glue"

echo implode(', ', $finalarray);
Sean Huber