I am not sure how clear my question is? But let me explain further. Before a person answers the test the result should be hyphen (-), When the person answers the test and gets a score it should display the score he has received. Now that was all working fine. But I noticed that when I score 0 It still displays as hyphen (-) when it should display 0. I will post my code below:
CODE:
<?php
if($skillsets)
foreach($skillsets as $skill => $percentage){ ?>
<div class="skill_block">
<div class="small"><?php echo $skill ?></div>
<?php if($percentage === 0) { ?>
<div class="big">0%</div>
<?php } else if($percentage == NULL) { ?>
<div class="big">-</div>
<?php } else { ?>
<div class="big"><?php echo $percentage ?>%</div>
<?php } ?>
</div>
<?php } ?>
Any help will be greatly appreciated. Thanks
19/01/2016
UPDATE:
The type of $percentage
is float
<?php
if(!empty($skillsets)){ # added { in condition
foreach($skillsets as $skill => $percentage)
{ ?>
<div class="skill_block">
<div class="small"><?php echo $skill ?></div>
<?php
if($percentage == 0 || empty($percentage)) # Changed
{
?>
<div class="big">0%</div>
<?php
}
else { ?>
<div class="big"><?php echo $percentage ?>%</div>
<?php
} ?>
</div>
<?php
}
}
else
{
echo "skillsets is empty";
}
try it like this:
<?php
if($skillsets){
foreach($skillsets as $skill => $percentage){ ?>
<div class="skill_block">
<div class="small"><?php echo $skill ?></div>
<?php if(!isset($percentage) || $percentage === NULL) { ?>
<div class="big">-</div>
<?php } else if($percentage == 0) { ?>
<div class="big">0%</div>
<?php } else { ?>
<div class="big"><?php echo $percentage ?>%</div>
<?php } ?>
</div>
<?php }
} ?>
You can use like that:
<?
if($skillsets){
foreach($skillsets as $skill => $percentage)
{
?>
<div class="skill_block">
<div class="small"><?php echo $skill ?></div>
<?php if(empty($percentage) || $percentage == NULL) { ?>
<div class="big">-</div>
<?php
}
else { ?>
<div class="big"><?php echo $percentage."%" ?></div>
<?php
}
?>
</div>
<?php
}
}
else
{
echo "No skills found";
}
?>
I'm assuming you're fetching these scores from a database ... when you do that, NULLs will be nulls, but integers will be string representations of numbers. Hence, your first check fails because you actually have string '0' instead of integer 0
; then, as already pointed out by others - == NULL
will match all "empty" values, such as NULL, FALSE, string '0', integer '0', etc.
You should do this:
<?php
if($skillsets)
{
foreach($skillsets as $skill => $percentage)
{
// isset() checks if a variable exists and is not null
if (isset($percentage))
{
$percentage = $percentage.'%';
}
else
{
$percentage = '-';
} ?>
<div class="skill_block">
<div class="small"><?php echo $skill; ?></div>
<div class="big"><?php echo $percentage; ?></div>
</div>
<?php
}
}
?>