在PHP中的FOREACH循环中使用IF语句

时间:2016-02-03 15:01:28

标签: php foreach

我试图执行以下代码,但它无效:

<?php foreach($reciepts as $value) { 
    $extension = get_file_extension($value);
    if($extension == "pdf") { ?>
        <p>Receipt:</p><br><embed src="<?php echo $value; ?>">
    <?php }
    else { ?>
        <p>Receipt:</p><br><img style="max-width:500px; max-height:500px;" src="<?php echo $value; ?>" />
    <?php } ?>

此案例中的$reciepts数组是:

[7] => Array
            (
                [0] => http://coppermountain.co.uk/wp-content/uploads/gravity_forms/12-c07945f2e8e37e124bd5be2c8a979300/2016/02/Screen-Shot-2016-02-01-at-09.33.18.png
                [1] => http://coppermountain.co.uk/wp-content/uploads/gravity_forms/12-c07945f2e8e37e124bd5be2c8a979300/2016/02/Expenses-1.pdf
            )

获取文件扩展名的功能:

function get_file_extension($value) {
    return substr(strrchr($value,'.'),1);
}

到目前为止我进行的测试:

$extension = $form_data['field'][7][1];
echo get_file_extension($extension);

$extension按预期回应pdf

如果我不包含如下IF / ELSE语句,那么循环也可以正常工作:

<?php foreach($reciepts as $value) { ?>
    <p>Receipt:</p><br><img style="max-width:500px; max-height:500px;" src="<?php echo $value; ?>" /> 
<?php } ?>

由于

1 个答案:

答案 0 :(得分:1)

你错过了foreach循环的近距离支撑,以下工作。

<?php
function get_file_extension($value)
{
    return substr(strrchr($value, '.'), 1);
}

$reciepts = [
    'http://coppermountain.co.uk/wp-content/uploads/gravity_forms/12-c07945f2e8e37e124bd5be2c8a979300/2016/02/Screen-Shot-2016-02-01-at-09.33.18.png',
    'http://coppermountain.co.uk/wp-content/uploads/gravity_forms/12-c07945f2e8e37e124bd5be2c8a979300/2016/02/Expenses-1.pdf'
];
foreach ($reciepts as $value) {
    $extension = get_file_extension($value);
    if ($extension == "pdf") {
        ?>
        <p>Receipt:</p><br><embed src="<?php echo $value; ?>">
    <?php } else {
        ?>
        <p>Receipt:</p><br><img style="max-width:500px; max-height:500px;" src="<?php echo $value; ?>" />
    <?php
    }
}//added missing brace
?>