hello,

i want to arrange variables in array from foreach loop like this

foreach($arr as $array){

$variable['first']      = $array['im'];  //first record from im column in a table  
$variable['second']= $array['im']; //2nd record from im column in a table  
}
echo $variable['first'];
echo $variable['second'];

the purpose is to make the variable available outside the loop without looping. any idea please....

Dani AI

Generated

Your code is fine in principle — you just need to collect the thumbnails into an indexed container while you fetch them, then read them by index outside the loop. Also note that the SQL you showed uses a specific img_id (usually a single-row result); if you expect multiple images you need to query the rows that actually return multiple records (change the WHERE clause or remove it).

A concise, modern approach is: fetch rows into an array, extract the thumbnail column, then access positions 0 and 1 for the first and second image. Example (using mysqli and different variable names than the original post):

$result = $mysqli->query("SELECT img_thumbnail FROM images WHERE whatever_condition");
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$thumbnails = array_column($rows, 'img_thumbnail');

echo $thumbnails[0] ?? 'no first image';
echo $thumbnails[1] ?? 'no second image';

If you prefer named keys like image1, image2, build them inside the loop with a counter:

$pics = [];
$n = 1;
while ($r = $result->fetch_assoc()) {
    $pics['image' . $n] = $r['img_thumbnail'];
    $n++;
}
echo $pics['image1'] ?? null;

Notes and troubleshooting: as pointed out, indexed access ($array[0], $array[1]) works and is simplest. Always check the result count ($result->num_rows or count($thumbnails)) before printing indexes to avoid notices. Avoid the old mysql_* extension — use MySQLi or PDO and prepared statements for safety and compatibility (see the MySQLi manual and array_column). If only two images are needed, use LIMIT 2 in the query to save work.

i dont really understand. Couldnt you just use

$arr[0] or $arr[1]

to get the variable?

actually, the full code is just like that,

$sql = "SELECT img_id, img_thumbnail FROM images WHERE img_id = 15";
$result = mysql_query($sql) or die ('list fail' .  sql_erroe());
while($row = mysql_fetch_array($result)){
$arr[]=$row;
}

foreach($arr as $array){

$param['image1] = $array['img_thumbnail'];  //first image thumbnail  from image column in a mysql table  
$param['image2'] = $array['img_thumbnail']; //2nd image thumbnail from image column in a mysql table  
}
echo $param['image1'];
echo $param['image2'];

hope the above code will clear the requirement..

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.