2016-07-07 91 views
0

我是PHP新手,我知道这很简单,但仍然找不到解决方案。echo array null values

我有保存4个不同的图像阵列,我想呼应的结果 所以我的HTML看起来像这样:

<img src="<?php echo $results['image1']?>" > 
<img src="<?php echo $results['image2']?>" > 
<img src="<?php echo $results['image3']?>" > 
<img src="<?php echo $results['image4']?>" > 

但如果例如图像4为空呢? - 我不想回显整个 <img src>标记行

我该怎么办? 谢谢?

回答

1

这是你的工作范例。

<?php 
if(!empty($results['image1'])) echo '<img src="'.$results['image1'].'">'; 
if(!empty($results['image2'])) echo '<img src="'.$results['image2'].'">'; 
if(!empty($results['image3'])) echo '<img src="'.$results['image3'].'">'; 
if(!empty($results['image4'])) echo '<img src="'.$results['image4'].'">'; 
?> 

试试这个代码可能会帮助你。这里我先检查一下,如果结果不是空的。

1
<?php if(isset($results['image1']) && !empty($results['image1'])){ ?><img src="<?php echo htmlspecialchars($results['image1']}; ?>" ><?php } ?> 
<?php if(isset($results['image2']) && !empty($results['image2'])){ ?><img src="<?php echo htmlspecialchars($results['image2']}; ?>" ><?php } ?> 
<?php if(isset($results['image3']) && !empty($results['image3'])){ ?><img src="<?php echo htmlspecialchars($results['image3']}; ?>" ><?php } ?> 
<?php if(isset($results['image4']) && !empty($results['image4'])){ ?><img src="<?php echo htmlspecialchars($results['image4']}; ?>" ><?php } ?> 
0
<?if(isset($results['image1']) && $results['image1'] != ""){?><img src="<?=$results['image1']?>" ><?}?> 

用这个,你检查它的图像设置。为每张图片做这件事,你应该没问题。
isset是没有必要的,但一些PHP的设置没有它会发出警告。因此,最好使用它。

如果你不希望所有的短标签,像这样做:

if(isset($results['image1']) && $results['image1'] != ""){echo "<img src='{$results['image1']}' >"; } 

这应该是你可以做的最高档。 "x{$variable}y"的工作原理与"x".$variable."y"类似,但如果您喜欢,则更容易编写/读取。