简体   繁体   中英

Automating IF statements

I am working on page where are multiple variants of same product. I'm using if statements to check if there is some change to show. However, as you can see I am repeating pretty much the same thing with if statements. How can I automate multiple if statements to a one?

Something like this:

if($s->??? !=0 ) {
    product->??? = $s->???;
} 

My code:

while ($s = $subProduct->fetch(PDO::FETCH_OBJ)) {

    $product->variant = $s->variant;

    if ($s->price != 0) {
        $product->price = $s->price;
    }
    if ($s->battery != 0) {
        $product->battery = $s->battery;
    }
    if ($s->topspeed != 0) {
        $product->topspeed = $s->topspeed;
    }
    if ($s->range != 0) {
        $product->range = $s->range;
    }
}

You can use get_object_vars .

$vars = get_object_vars($s);
foreach($vars as $key => $value) {
    if($s->$key != 0) 
        $product->$key = $s->$key;
}

i'm sure that there are plenty of options, but just to maybe give you an idea:

$optionalParams = array("range","topspeed","price","battery");
foreach($optionalParams as $option) { 
 if(isset($s->$option) && $s->$option != 0)
  $product->$option = $s->$option;
}

As of PHP 5 you can just use object iteration

just by doing that

foreach ($v as $key => $prop){
    if ($prop != 0){
        $v->$key = $s->battery;
    }
}

Full code example

<?php
$v= new \stdClass();
$v->name = "john";
$v->age = 30;

foreach ($v as $key => $prop){
    if ($prop){
        $v->$key = "changed";
    }
}
var_dump($v);
exit;

Now, all $v properties is "changed"

See the code as demo ( https://eval.in/833456 )

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