PHP array: content from a result set

I have a pretty simple problem to which I could not find a solution. I would like to populate the array with the contents of the mySQL column.

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

    foreach ($results as $row){

      $names = array();

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

    };

Suppose that in the result set there were 40 names that should now be in the $ names array, but I get the last result when I try to print the contents on the screen:

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

I also tried:

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

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

    }

However, I already have the foreach setup and work, so I don’t want to enter another loop to fill the array.

I know that the query and the loop work, because I can output the value of each name directly by setting:

    echo $row['name'] 

loop and see how the resulting names are printed on the screen.

+3
4

Try

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

$names , , .

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

, $names = array(); ,

+3

You redefine the value of the array each time, initializing it inside the loop. The following will work:

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

Otherwise, you click on the first iteration and clear it again, again and again.

+3
source

You declare a variable in a loop and want to use it beyond its impossibility. Read about php variable scope.

0
source

All Articles