PHP - Add String to Array

10,698

Solution 1

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

Solution 2

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

$array = array('foo');

$array[] = 'bar'.

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

Solution 3

You can use the function array_push or [] notation:

array_push($array, 'hi');

$array[] = 'hi';

Solution 4

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:
10,698

Related videos on Youtube

lab12
Author by

lab12

Updated on June 04, 2022

Comments

  • lab12
    lab12 almost 2 years

    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

  • lab12
    lab12 over 13 years
    If I add the two brackets, my array is a list of strings that say "Array" over and over again.
  • Gromski
    Gromski over 13 years
    @Kevin Could you show us the actual code with which this is happening?
  • NDEIGU
    NDEIGU almost 9 years
    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?