php - Display data from variables with condition

980

I've a question for you if you can help me, I've some variables that I retrieve with them data from database, but I want to resolve this problemif all the variables are empty then show something if not then show the just the variables that have data.

The Code is:

foreach ($row as $result) {
  if ($row[29] == '') {
    $string29 = '';
  }else if ($row[29] == 0){
    $string29 = '';
  } else{
    $string29 = '<div ><h1>Pression</h1><img src="images/'.$row[29].'.png"></div>';
  }
}

foreach ($row as $result) {
  if ($row[30] == '') {
    $string30 = '';
  }else if($row[30] == 0){
    $string30 = '';
  } else{
    $string30 = '<div ><h1>Fixation</h1><img src="images/'.$row[30].'.png"></div>';
  }
}

`

Then I haveecho &string29 and so on........

307

Answer

Solution:

Your code is rather redundant. By PHP typecasting rules,0 and'' are actually loosely equal:

php > var_dump(0 == '');
bool(true)

What you should be doing is have an array of keys/names you could loop over, e.g:

$fields = array(29 => 'Pression', 30 => 'Fixation');

foreach ($fields as $key => $field) {
   if ($row[$key]) { .... }
   echo '...';
}

People are also looking for solutions to the problem: cannot find the variables in php session

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.