Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Is there a way, to write this if/elseif/else statement shorter?

So I have been actively learning PHP for the past days and, for practise, I wrote PHP script, which takes HTML Form values.

I tried writing script, where I have 5 persons, and you have to input your name and last name. If it matches with one of the five persons, it sends one message, if not, other. Here it is (Without form part, only PHP):

    $first = $_POST["first"];
    $last = $_POST["last"];

    if ($first == "Jeb") {
        if ($last == "Jeb") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Bob") {
        if ($last == "Bob") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Bill") {
        if ($last == "Bill") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Annie") {
        if ($last == "Annie") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Hugo") {
        if ($last == "Hugo") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } else {
        print "I dont know you!";
    }

It works great, but I have question- can this be done easier / written shorter? And can this be done using switch statement?

Any respone will be apprecieted!

like image 651
Zeo Avatar asked Dec 06 '25 10:12

Zeo


2 Answers

i can see a way using arrays

$people=array('Bob Bob', 'Bill Bill');//etc

if(in_array($first.' '.$last,$people)){
 print "Hello!";
}else{
   print "I dont know you!";
}

A solution using arrays. Assumes all known names are pairs of the same name (bob bob, jeb jeb, etc)

$knownNames = array("Jeb", "Bob", "Bill", "Annie", "Hugo");
if (in_array($first, $knownNames) && $first == $last)
  print "Hello!";
else
  print "I don't know you!"
like image 24
CollinD Avatar answered Dec 08 '25 00:12

CollinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!