How to add to an array inside of loop

I’m trying to loop through mysql query results inside of a loop and add them to an array.

//initialize array
$people = array();

//build array of names & numbers
while ($row = mysql_fetch_assoc($result))  
{ 
	$to = $row['text'];
	$fname = $row['fName'];

	$people = array(
        $to => $fname
    );
}

Not sure what I’m doing wrong…

What I do is build a temporary array within the loop, then add that to the parent array at the end.

while($row = $sql->fetch()) {
	$temp['to'] = $row['text'];
	$temp['fname'] = $row['fName'];
        // Etc...

	$people[] = $temp;
        $temp = NULL ; // reset the temp array at end of loop
}

Maybe

	$people[] = array(
        $to => $fname
    );

Also look at moving on from the old-style MySQL library calls to access the database, either to mysqli or PDO.

1 Like

It really depends on the exact structure of data you want to end up with.
Simply taking one array ($row) and putting it into another identical array called $people is kind of pointless. So I presume there is some further processing of the data going on.

I’m going to use the array in a for loop. The format of the array should be:

$people = array(
        "5558675309" => "Aaron",
        "6666666666" => "Joe",
        "4444444444" => "Jane"
    );

foreach ($people as $number => $name) {
   ...
}

That should be simple enough.

{ $people[$row['number']] = $row['fname']; }

Sorry, but I’m still not sure…

Is this what you mean?

$result = mysql_query($query);

$people = array();
while ($row = mysql_fetch_assoc($result))={ 
	$people[$row['number']] = $row['fname']; 
}

Yes. But no need to create the array before the while.
Going by your first post, number shoud be text. I just made up that column name. :shifty:

Thanks that got it working!

  1. Forget mysql_fetch_assoc().
  2. Forget loops.

mysql_fetch_assoc(), along with all its sister functions has been removed from PHP a year ago. Not to mention there are other ways to get what you want right from the query, without any loops at all. Namely PDO.

$stmt = $pdo->query("SELECT number, fname FROM whatever")
$people = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

This. Is. All.

You can learn more about PDO from the tutorial I wrote

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.