开发者

PHP if statement not working?

// 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";} 

This Output will show:

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

However, my problem is if $field3, $field4, and 开发者_开发百科$field5 are NULL, I don't want to display $rowField2 including the text "From 1st Row continued"

I tried IF/ELSE and ISSET procedure:

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

But $rowField2 still shows "From 1st Row continued". I want it not to display that if the last 3 fields are NULL.


Try this it will give output as "apple, orange".

is it fine?

<?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;
?>


I would have used condition :

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


$stringList will always be set, but it won't always have content in it.

Don't use empty because it's not clear from reading it what it does — for one thing, empty("0") is TRUE! — , even though in this case, on an array, it would work.

My recommended approach:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜