2

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

6 Answers 6

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

$array = array('foo');

$array[] = 'bar'.

// $array == array('foo', 'bar')

2 Comments

If I add the two brackets, my array is a list of strings that say "Array" over and over again.
@Kevin Could you show us the actual code with which this is happening?
3

You can use the function array_push or [] notation:

array_push($array, 'hi');

$array[] = 'hi';

1 Comment

what is this code actually doing? I don't get why you "push" 'hi' to array, but then you assign hi to the end of the array. Aren't you essentially adding it twice, then?
1

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";

Comments

0

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];

Comments

0
echo implode($finalarray);

Or with a custom join "glue"

echo implode(', ', $finalarray);

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.