Reputation: 59
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;
}
}
Upvotes: 0
Views: 74
Reputation: 7523
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)
Upvotes: 0
Reputation: 8060
You can use get_object_vars.
$vars = get_object_vars($s);
foreach($vars as $key => $value) {
if($s->$key != 0)
$product->$key = $s->$key;
}
Upvotes: 1
Reputation: 1416
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;
}
Upvotes: 0