PHP if语句不起作用?

时间:2011-07-05 06:23:57

标签: php arrays

// 40 characters string combine by 5 different fields
$field1 = apple;
$field2 = orange;
$field3 = pineapple;
$field4 = banana;
$field5 = strawberry;

// fields will be separated with a comma
$string = implode(", ", array_filter(array($field1, $field2, $field3, $field4, $field5)));

// string will be cut off at about 15th characters then make a break line           
$stringList = explode("\n", wordwrap($string , 15));

// 1st rowField takes the 1st line of string
$rowField1 = array_shift($nutritionalList);
$string = implode(" ",$stringList );
$stringList = explode("\n", wordwrap($string , 25));
$rowField2 = "From 1st Row continued" . "\n" . implode("\n", $stringList) . "\n \n";} 

此输出将显示:

$rowField1 = "apple, orange"
$rowField2 = "From 1st Row continued \n pineapple, banana, strawberry"

但是,我的问题是如果$field3$field4$field5为NULL,我不想显示$rowField2,包括文字“From 1st Row续“

我尝试了IF / ELSE和ISSET程序:

if (isset($stringList)) {
   $rowField2 = "From 1st Row continued\n" . implode("\n", $stringList) . "\n\n";
}
else {
   $rowField2 = NULL;
}

但是$rowField2仍然显示“从第一行继续”。如果最后3个字段为NULL,我希望它不显示。

3 个答案:

答案 0 :(得分:3)

试试这个,它会输出“apple,orange”。

没事吗?

<?php
$field1 = 'apple';

$field2 = 'orange';

$field3 = '';

$field4 = '';

$field5 = '';

// fields will be seperated with a comma

$string = implode(", ", array_filter(array($field1, $field2, $field3, $field4, $field5)));

// string will be cut off at about 15th characters then make a break line

$stringList = explode("\n", wordwrap($string , 15));

// 1st rowField takes the 1st line of string

$rowField1 = array_shift($stringList);

$string = implode(" ",$stringList );

$stringList = explode("\n", wordwrap($string , 25));

$rowField2 = ( isset( $stringList[0] ) && !empty($stringList[0]) ) ? "From 1st Row continued" . "\n" . implode("\n", $stringList) . "\n \n" : '';
echo $rowField1;
echo "<br />";
echo $rowField2;
exit;
?>

答案 1 :(得分:1)

我会使用条件:

if( isset($stringList) && count($stringList) > 0 ){
    // blah blah
}

答案 2 :(得分:0)

$stringList将始终设置,但它并不总是包含内容。

不要使用empty,因为通过阅读它不清楚它是做什么的 - 一方面,empty("0")TRUE! - 即使在这种情况下,在数组上,它也可以工作。

我推荐的方法:

if (count($stringList)) {
   $rowField2 = "From 1st Row continued\n" . implode("\n", $stringList) . "\n\n";
}
else {
   $rowField2 = NULL;
}