Jump to content

how to compress isset statements?


blackhawk

Recommended Posts

I have code that i wrote to check if all the values are false (not just one of them)....

 

 

     if (!isset($orange[0]['my_id']) &&
        !isset($red[0]['my_id']) &&
        !isset($blue[0]['my_id']) &&
        !isset($green[0]['my_id']) &&
....

print "none of the colors are set";
}

 

how can i compress this !isset batch to one line rather than multiple isset lines? I was thinking

 

$nocolorsset = '';
foreach($color as $key=>$value ) { 	
if (!isset($color[$key][0]['my_id'])) {
  $nocolorsset = 'none of the colors are set';
}
}
print $nocolorsset;

 

but that checks each $color value individually. I want to check if all the values together are not set. In other words if one of the colors is set, $nodropship will remain blank;

 

thanks!

Link to comment
https://forums.phpfreaks.com/topic/187311-how-to-compress-isset-statements/
Share on other sites

I would recommend using an array instead of 4 variables BUT, if you wanted to to be more dynamic you could do this

<?php
$orange[0]['my_id'] = 1;
$red[0]['my_id'] = 2;
$blue[0]['my_id'] = 3;
$green[0]['my_id'] = 4;

$nocolorsset = '';
$color = array('orange','red','blue','green');
foreach($color as $value) {
$val = $$value; //this is the key behind it all (a variable variable) 
if (empty($val[0]['my_id'])) {
	$nocolorsset = 'none of the colors are set';
}
}
print $nocolorsset;

more info here

http://www.php.net/manual/en/language.variables.variable.php

thank you so much for that start - i actually have my array in good shape with your idea tweeked -

 

function seekKey($array, $key, $value)
{
    $ret = array();
    for ($i=0;$i<count($array);$i++)
    {
        if ($array[$i][$key]==$value)
            $ret[] = $array[$i];
    }
    return $ret;
}


foreach($colors as $key=>$value ) { 	
	if(empty($colors[$key])) {
     unset($colors[$key]);     
	}else{
		$colors[$key] = seekKey($colors[$key], 'this is a special color', '1'); 	
  }
}


$nocolor = '';
foreach($colors as $key=>$value) {
if (empty($colors[$key])) {
$nocolor = '<h2 class="nocolor">No Color is set</h2>';
}
}
print $nocolor;

 

I'm checking my associative array against a function called seekKey. and if it doesnt find any key value pairs with 'this is a special color' then it unsets that sub array from my main array.  Then if any sub arrays left over contain an empty key then display no color is set only once.  Just what I needed.  Thanks again!

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.