3

I have a fairly simple problem to which I've been unable to find a solution. I'd like to fill an array with the contents of a mySQL column.

Basically I have a loop that gathers the result set, and I need to take a specific column from this result set and put it into an array.

    foreach ($results as $row){

      $names = array();

      $names[] = $row['name'];

    };

Let's say there were 40 names in the result set they should now all be in the $names array, but I only get the last result when I attempt to print the contents on screen:

    echo $names[0]; or print_r($names);

I have also tried:

    while($row = mysql_fetch_array($results)) {

       $names[] = $row['name']; 

    }

However I already have the foreach setup and working so I don't want to introduce another loop just to populate the array.

I know the query and loop are both working because I can echo out the value of each name directly by placing:

    echo $row['name'] 

in the loop and see the resulting names print on screen.

1
  • On your first example, you're resetting the array on every loop iteration, so you'd only ever get the LAST record retrieved from the DB stored into it. The initialization must be done OUTSIDE the loop. Commented May 8, 2012 at 20:49

4 Answers 4

5

Try

$names = array();
foreach ($results as $row){
      $names[] = $row['name'];
}

You were re-declaring $names to a blank array on each loop removing the item you added to it.

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

1 Comment

That's definitely going to be your problem. Every re-looping, the $names array was getting emptied; if you put it outside the loop, it stops doing that.
3
$names = array();
foreach ($results as $row){
    $names[] = $row['name'];
};

your problem was $names = array(); was declaring a new array everytime you looped through the result set

Comments

3

You are overriding the array value each time by initializing it inside of the loop. The following will work:

$names = array(); //Outside
foreach ($results as $row){
      $names[] = $row['name'];
}

Otherwise, you're pushing on the first iteration, and clearing it on the next, over and over again.

Comments

0

You are declaring variable in a loop and want to use it outside its impossible. Read about php variables scope.

1 Comment

If that were true, then he wouldn't be getting any data at all, instead of just getting the final value.

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.