In php file while loop is used to populate data in array in a following
way,

$result = mysql_query($sql ) or die ('Error, list failed. ' . mysql_error());

while($row = mysql_fetch_array($result))
 {
  $row[tableLegends];
  $link[]=$row;
  }

and for loop is used in printing data in theme file

for ($j=0; $j<count($link); $j++) 
{
echo $link[$j]['f_name']; 
echo $link[$j]['l_name'];

------code here-------

}

Actually, I want to use foreach loop in place of for loop.

Any idea please..

Dani AI

Generated

Both and pointed in the right direction: foreach is the natural replacement for an index-based for loop. A few practical tips that were not shown in the replies make the change more robust and future‑proof. Prefer associative-only fetches so you do not get duplicate numeric keys, move away from the old mysql_* extension (it was removed in PHP 7), and decide whether you need to buffer all rows in memory or stream them one-by-one for large result sets.

Example using mysqli and a buffered result (keeps a numeric index if you need it):

$mysqli = new mysqli($host, $user, $pass, $db);
$result = $mysqli->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC); // associative array
foreach ($rows as $i => $row) {
    printf("%d: %s %s\n", $i + 1, $row['f_name'], $row['l_name']);
}

If the result set may be large, stream rows instead of calling fetch_all:

$stmt = $mysqli->query($sql);
while ($row = $stmt->fetch_assoc()) {
    // process row immediately; no big array in memory
}

Quick troubleshooting: check is_array() or !empty() before iterating to avoid warnings; use prepared statements for variable input; and consult the PHP docs for foreach and migration guidance when moving from mysql_* to mysqli/PDO (foreach docs, migration notes for mysql removal).

Recommended Answers

All 2 Replies

Try the following:

foreach ($link AS $links) {
echo $links['f_name']; 
echo $links['l_name'];
}

Hi,

You could replace your for loop with a foreach loop such as:

foreach($link as $arrLink) {

    echo $arrLink['f_name']; 
    echo $arrLink['l_name'];
    ------code here-------

}

Hope this helps.

R.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.