简体   繁体   中英

how to store isset condition php to avoid repetition

my code:

if (isset($dayMarks[$res['resId']][$dDate])) {
     $var=$dayMarks[$res['resId']][$dDate];
     echo $var;
}

note that the isset condition is identical to the value assigned to $var, which creates a pretty ugly code.

How is it possible to assign the condition to $var without repeating it?

(in javascript, I'd write if (var=$dayMarks[$re...) )

This is a common problem in PHP where including files can create uncertainty about variables.

There are a two approaches that work well for me.

Default Assignment

With default assignment the $var variable will be given a default value when the key doesn't exist.

$var = isset($dayMarks[$res['resId']][$dDate]) ? $dayMarks[$res['resId']][$dDate] : false;

After this code can assume that $var will always contain a valid value.

Default Merger

My preferred method is to always declare a default array that contains all the required values, and their defaults. Using the False value to mark any keys that might be missing a value (assuming that key holds another value type besides boolean).

$default = array(
    'date'=>false,
    'name'=>'John Doe'
);

$dayMarks[$res['resId']] = array_merge($default, $dayMarks[$res['resId']]);

This will ensure that the required keys for that variable exist, and hold at least a default value.

You can now test if the date exists.

if($dayMarks[$res['resId']]['date'] !== false)
{
     // has a date value
}

While this might not work exactly for your array. Since it looks like it's a table structure. There is a benefit to switching to named key/value pairs. As this allows you to easily assign default values to that array.

EDIT:

The actual question was if it was possible to reproduce the JavaScript code.

if (var=$dayMarks[$re...)

Yes, this can be done by using a helper function.

NOTE: This trick should only be used on non-boolean types.

 function _isset($arr,$key)
 {
    return isset($arr[$key]) ? $arr[$key] : false;
 }

 $a = array('zzzz'=>'hello');
 if(($b = _isset($a,'test')) !== false)
 {
    echo $b;
 }
 if(($c = _isset($a,'zzzz')) !== false)
 {
    echo $c;
 }

See above code here

$isset = isset(...); //save the value
if ($isset) { .... }; // reuse the value
...
if ($isset) { ... }; // reuse it yet again

The only thing you can do is store $res['resId'][$dDate] .

$var = $res['resId'][$dDate];
if( isset($dayMarks[$var]) ) {
    $var = $dayMarks[$var];
    echo $var;
}

If you only want to assign a variable processing simply, you can also write this as:

$var = $dayMarks[$res['resId']][$dDate]);
if (!isset($var)) unset($var);

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