Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple way to write large elseif statements in PHP

Tags:

html

php

I'm getting post values from an emailer form and I set all the option values to numbers and I'm trying to convert them to their actual strings to send in an email. I need to make this code easier to use.

if ($subject == "1") {
$sub = "General Questions"; 
} elseif($subject == "2") {
$sub = "Membership";
} elseif($subject == "3") {
    $sub = "Club Fees";
} elseif($subject == "4") {
    $sub = "Proshop & Lessons";
} elseif($subject == "5") {
    $sub = "Events"; 
} elseif($subject == "6") {
    $sub == "Leagues & Programs";
} elseif($subject == "7") {
    $sub == "Resturant & Bar";
};

Maybe I could set the value='' to the actual values and skip this part all together.

like image 528
Kyle Monti Avatar asked Dec 01 '22 22:12

Kyle Monti


2 Answers

Why not make an associative array?

$subs = array(
  1 => 'General Questions',
  2 => 'Membership',
  3 => 'Club Fees',
  4 => 'Proshop & Lessons',
  // others.
);

$sub = isset($subs[$subject]) ? $subs[$subject] : 'Default Value';
like image 139
Brad Christie Avatar answered Dec 31 '22 19:12

Brad Christie


One way to rewrite is to use the switch statement in PHP. You can read more about it here.

like image 40
Waynn Lue Avatar answered Dec 31 '22 18:12

Waynn Lue