数组中的PHP条件

时间:2015-05-01 11:38:56

标签: php

是否可以在数组中使用条件:

Uses define('COMPANY_ADDRESS_1','something here'); << if empty don't want to be in the array
$invoice->setFrom(array(COMPANY_NAME,COMPANY_ADDRESS_1,COMPANY_ADDRESS_2,COMPANY_TOWN,COMPANY_COUNTY,COMPANY_POSTCODE));

例如,COMPANY_ADDRESS_2未设置且未在数组中显示,因此输出结束时如下:

  • 公司名称
  • 公司地址1
  • &LT;&LT;&LT;&LT;&LT;&LT;&LT;&LT;&LT;&LT;这里留下了空白
  • 公司镇
  • 公司县
  • 公司邮政编码

输出正常但是如果没有设置例如COMPANY_ADDRESS_2我想将它从数组中完全删除,因为它被传递给PDF生成器并且当前写为空行。

1 个答案:

答案 0 :(得分:1)

根据您的问题,我认为您的阵列如下所示: -

Array
(
    [0] => company name
    [1] => company address 1
    [2] => 
    [3] => company town
    [4] => company county
    [5] => company postcode
)

所以你需要按照以下方式做: -

<?php

$result = array('company name','company address 1','','company town','company county','company postcode');//original array
$newArray = array();
foreach($result as $value){
    if($value != ''){
        $newArray[] = $value;
    }
}
echo "<pre/>";print_r($newArray);
echo "<pre/>";print_r(array_filter($result));
?> 

输出: -

Array //null value or empty value removed and array is re-indexed
(
    [0] => company name
    [1] => company address 1
    [2] => company town
    [3] => company county
    [4] => company postcode
)

Array //null value or empty value removed without re-indexed
(
    [0] => company name
    [1] => company address 1
    [3] => company town
    [4] => company county
    [5] => company postcode
)