$counter = "";
if($sWall>1){
$count开发者_如何学Pythoner = $counter + $sWall;
}
if($sWC>1){
$counter = $counter + $sWC;
}
if($sOther>1){
$counter = $counter + $sOther;
}
if(!(empty($counter))){
echo "(".$counter.") ";
}
This is what I have that does not work.
$sOther
, $sWC
, $sWall
is mysql_num_rows
. I wish to echo out e.g (3) if you have 1 in $sOther
, 1 in $sWC
and 1 in $sWall
.
How can I do that, what I did is just something I tried.
Counter is a string type. First line should be $counter = 0;
.
And you should change if ($sWall>1)
to if ($sWall>0)
and so on...
$counter = $sWall + $sWC + $sOther;
if ($counter) {
echo '(' . $counter . ')';
}
That's it ;) Remember: Short code is good code.
In the code above, $counter will not increment if any of the checked values are equal to 1. You should use if($sWall*>=*1). It might be even easier to simply add $sWall + $sWC + $sOther
$counter = 0;
if($sWall>0){
$counter = $counter + $sWall;
}
if($sWC>0){
$counter = $counter + $sWC;
}
if($sOther>0){
$counter = $counter + $sOther;
}
if($counter>0){
echo "(".$counter.") ";
}
Use an int if you want to store numbers, so you can just check if it's greater than zero and echo it.
Note that you could also write $counter += $sWall;
instead of $counter = $counter + $sWall;
, so you don't have to type that much.
Initialize numeric values to 0
. This isn't the source of your problem, as PHP will convert the empty string to 0
for you when you use numeric operators like +
, but symantically it's better to state up front that $counter
is numeric.
Once you've added your values, test if $counter
is greater than 0 rather than using empty
. You can use shorthand +=
operators and simply test $counter
to make the whole method a little more succinct.
Finally, you've chosen the wrong comparison operator (>
) to test your values. If you want to include 1
, use >=
:
$counter = 0;
if($sWall >= 1) $counter += $sWall;
if($sWC >= 1) $counter += $sWC;
if($sOther >= 1) $counter += $sOther;
if ($counter)
echo "($counter)";
精彩评论