Reputation: 49
I have the following PHP code:
<?php
//code above
$pic_1 = $afil['image_1'];
$pic_2 = $afil['image_2'];
$pic_3 = $afil['image_3'];
$pic_4 = $afil['image_4'];
$pic_5 = $afil['image_5'];
$pic_6 = $afil['image_6'];
$pic_7= $afil['image_7'];
$pic_8 = $afil['image_8'];
$pic_9 = $afil['image_9'];
$pic_10 = $afil['image_10'];
if ($pic_1 = "")
{
$pic_1 = //defaultpic - to be defined, same as below
}
if ($pic_2 = "")
{
$pic_2 = //defaultpic
}
?>
Rather than repeat these "if" statements for each picture (up until $pic 10) i just wondered if somebody could point out a more elegant and efficient way of doing it. I am quite new to php and this is a new situation i have encountered. Thanks a lot in advance.
Upvotes: 2
Views: 135
Reputation: 5239
Use arrays
and loop through them with just 1 if
statement, like this,
foreach($afil as $k => $v) {
if(empty($v))
$afil[$k] = ...//default pic
}
Or, if you are keen to have an additional array $pics
(for future use maybe),
foreach($afil as $k => $v) {
$pics[$k] = $v;
if(empty($v))
$pics[$k] = ...//default pic
}
Also, =
is an assignment operator. For comparison (or condition check), you need to use ==
or ===
(type safe).
Edit:
$afil = mysql_query(...);
while($row = mysql_fetch_array($afil)) {
//In here, say you create an array $result_rows with all the rows
$result_rows[] = $row;
}
Then, use $result_rows
in the foreach.
Upvotes: 4