Reputation: 6697
Here is my code:
if ( $identity == "asker" ) {
$min_amount = 3000;
} elseif ( $identity == "supporter" ) {
$min_amount = 5000;
} elseif( $identity == "viewer" ) {
$min_amount = 7000;
} else {
throw new Exception('something went wrong');
}
$check_credit = $bounty->check_credit($min_amount);
if ($check_credit["status"] == 1) {
if ( $identity == "asker" ) {
$make_bounty_system["content"] = $bounty->make_devote_html($check_credit["amount"], $identity);
} elseif ( $identity == "supporter" ) {
$make_bounty_system["content"] = $bounty->make_devote_html($check_credit["amount"], $identity);
} elseif( $identity == "viewer" ) {
$make_bounty_system["content"] = $bounty->make_devote_html($check_credit["amount"], $identity);
} else {
throw new Exception('something went wrong');
}
}
As you can see, the same logic ($identity == ?
) is repeated twice. Any idea how can I write the same code cleaner?
Upvotes: 2
Views: 167
Reputation: 3568
I think this question goes a bit deeper than just a switch case, but it's not immediately obvious from the way it's worded. What I think you're asking is how to avoid doing this both inside and outside of if ($check_credit["status"] == 1)
?
if ( $identity == "asker" )
Put your amounts in an array and reference them as needed. Also you don't need to repeat the code in the second if
just check if $identity
is a key in the array:
$amounts = [
"asker" => 3000,
"supporter" => 5000,
"viewer" => 7000
];
if(isset($amounts[$identity])) {
$check_credit = $bounty->check_credit($amounts[$identity]);
if ($check_credit["status"] == 1) {
$make_bounty_system["content"] = $bounty->make_devote_html($check_credit["amount"], $identity);
}
} else {
throw new Exception('Identity wrong!');
}
Upvotes: 4