简体   繁体   中英

skip row item if value empty using for loop php

I print some data using for loop.My code work corrcetly but I want to skip row if specific value will be empty

my code

$count = count($cd);
for ($i = 0; $i < $count; $i++) 
{

print'["'.$cd[$i][2].'", '.$cd[$i][4].', '.$cd[$i][5].','.$count.',"'.$cd[$i][8].'","'.$cd[$i][0].'", "'.strip_tags($cd[$i][3]).'","'.$cd[$i][6].'"]';

if ($i < ($count - 1))
 {
    echo ', ';
 }
}

If value of $cd[$i][2] and $cd[$i][4] will be blank the print skip this row

any idea

Skip the empty rows with by using if condition and check if not empty then print.

$count = count($cd);
for ($i = 0; $i < $count; $i++) 
{
   if(!empty($cd[$i][2]) && !empty($cd[$i][4]))
     print'["'.$cd[$i][2].'", '.$cd[$i][4].', '.$cd[$i][5].','.$count.',"'.$cd[$i][8].'","'.$cd[$i][0].'", "'.strip_tags($cd[$i][3]).'","'.$cd[$i][6].'"]';

   if ($i < ($count - 1))
   {
       echo ', ';
   }
}

Try like this:

$count = count($cd);
for ($i = 0; $i < $count; $i++) 
{
if(!empty($cd[$i][2]) && !empty( $cd[$i][4])) {

print'["'.$cd[$i][2].'", '.$cd[$i][4].', '.$cd[$i][5].','.$count.',"'.$cd[$i][8].'","'.$cd[$i][0].'", "'.strip_tags($cd[$i][3]).'","'.$cd[$i][6].'"]';


if ($i < ($count - 1))
 {
    echo ', ';
 }
}
}

There are multiple approaches to check if something is "blank":

  1. if(empty($var)) - empty($var) is true if the variable is not set , or it has an empty value (empty = empty string OR zero OR null OR false )

  2. if(!strlen($var)) - this is almost the same, except if variable is not set, you will get a warning, and zero is not empty value, obviousely in this case (as it checks length of the value).

  3. if(!isset($var)) - isset($var) is true if the variable is set, and false otherwise. So, !isset($var) is the exact opposite, because of negation.

So, depending on your definition of blank , You might need to check different things here. But in general, the condition would look like this:

for ($i = 0; $i < $count; $i++) 
{
   if(empty($cd[$i][2]) && empty($cd[$i][4])) continue; // skip this line entirely

   ... // the rest of your code in the loop
}

I've taken a little bit of a different approach from everyone else... (using foreach instead)

Take this for example:

$count = count($cd);
$i = 0;
$sep = ',';

foreach($cd as $item){
  if ($i == ($count - 1)){$sep = '';}

  if(!empty($item[2]) && !empty($item[4])){
    echo '["' . $item[2] . '", ' . $item[4] . ', ' . $item[5] . ',' . $count . ',"' . $item[8] . '","' . $item[0] . '", "' . strip_tags($item[3]) . '","' . $item[6] . '"]' . $sep;
  }else{
    $count --;
  }

  $i++;
}

Not too sure about whether it will be slower but I've always preferred a foreach statement to a for statement.

All criticisms welcome

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM