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

share|improve this question

6 Answers

up vote 4 down vote accepted

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..

share|improve this answer

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

$array = array('foo');

$array[] = 'bar'.

// $array == array('foo', 'bar')
share|improve this answer
If I add the two brackets, my array is a list of strings that say "Array" over and over again. – lab12 Aug 25 '10 at 3:12
@Kevin Could you show us the actual code with which this is happening? – deceze Aug 25 '10 at 3:14
Edited in the question. – lab12 Aug 25 '10 at 3:50

You can use the function array_push or [] notation:

array_push($array, 'hi');

$array[] = 'hi';
share|improve this answer

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";
share|improve this answer

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];
share|improve this answer
echo implode($finalarray);

Or with a custom join "glue"

echo implode(', ', $finalarray);
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.