Learning how to refactor PHP code
I'm using PHP 5.2.9 at the very moment. Is there a way to refactor this code this way it's easier to read and better organized?
if ($is_read_only == true) {
echo ($affiliate['affiliate_gender'] == 'm') ? MALE : FEMALE;
} elseif ($error == true) {
if ($entry_gender_error == true) {
echo tep_draw_radio_field('a_gender', 'm', $male) . ' ' . MALE . ' ' . tep_draw_radio_field('a_gender', 'f', $female) . ' ' . FEMALE . ' ' . ENTRY_GENDER_ERROR;
} else {
echo ($a_gender == 'm') ? MALE : FEMALE;
echo tep_draw_hidden_field('a_gender');
}
} else {
echo tep_draw_radio_field('a_gender', 'm', $male) . ' ' . MALE . ' ' . tep_draw_radio_field('a_gender', 'f', $female) . ' ' . FEMALE . ' ' . ENTRY_GENDER_TEXT;
}
Solution 1:
I'm not sure why you'd want it in fewer lines, but here you go:
echo $is_read_only === true
? $affiliate['affiliate_gender'] === 'm' ? MALE : FEMALE
: $error === true
? $entry_gender_error == true
? tep_draw_radio_field('a_gender', 'm', $male) . ' ' . MALE . ' ' . tep_draw_radio_field('a_gender', 'f', $female) . ' ' . FEMALE . ' ' . ENTRY_GENDER_ERROR
: ($a_gender === 'm' ? MALE : FEMALE) . tep_draw_hidden_field('a_gender')
: tep_draw_radio_field('a_gender', 'm', $male) . ' ' . MALE . ' ' . tep_draw_radio_field('a_gender', 'f', $female) . ' ' . FEMALE . ' ' . ENTRY_GENDER_TEXT;
It surely ain't more readable. Readability and compression seem to contradict each other.
EDIT:
For the challenge in it I went a bit further.
echo $is_read_only
? $affiliate['affiliate_gender'] === 'm' ? MALE : FEMALE
: $error && !$entry_gender_error
? ($a_gender === 'm' ? MALE : FEMALE) . tep_draw_hidden_field('a_gender')
: tep_draw_radio_field('a_gender', 'm', $male) . ' ' . MALE . ' ' .
tep_draw_radio_field('a_gender', 'f', $female) . ' ' . FEMALE . ' ' .
($error ? ENTRY_GENDER_ERROR : ENTRY_GENDER_TEXT);
This is the worst that I, as a human, can do.
May God have mercy on my soul :)
Solution 2:
you can change if ($is_read_only == true)
to if ($is_read_only)
as well as your other if statement because putting '== true'
is redundant and unnecessary