PHP: Switch() If{} other control structures

132 Views Asked by At

How do you execute logic with out the use of Switch or If?

For instance check_id_switch($id)

function check_id_switch($id){
    switch($id){
        case '1': 
        $HW = 'Hello, World!';
        break;
        default:
        $HW = 'Goodbye, World!';
        break;
     } 
  return $HW;
 }

Or instance check_id_if($id)

function check_id_if($id){
    if($id == 1){
     $HW = 'Hello, World!';
    }
   else{ 
   $HW = 'Goodbye, World!';
 }
return $HW;
}

Both of which functions check_id_switch($id) and check_id_if($id) will check the ID to it's reference.

How do I create the same logic as above without using if/switch statements in php? I would also like to avoid forloops.

There are multiple debates regarding performance for the switch/if but if there is another control structure does it under or out perform the aforementioned control structures?

Adding Login Script as an example of if statements. I've removed the backbone of the login script. You don't need to see the actions completed if true:false. I just feel that the below is clunky and unclean.

if(!empty($_POST))
{
    $errors = array();
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    $remember_choice = trim($_POST["remember_me"]);

    if($username == "")
    {
        $errors[] = ""; 
    }
    if($password == "")
    {

        $errors[] = "";
    }

    if(count($errors) == 0)
    {
        if(!usernameExists($username))
        {
            $errors[] = "";
        }
        else
        {
            $userdetails = fetchUserDetails($username);

            if($userdetails["active"]==0)
            {
                $errors[] = "";
            }
            else
            {
                $entered_pass = generateHash($password,$userdetails["password"]);

                if($entered_pass != $userdetails["password"])
                {
                    $errors[] = "";
                }
                else
                {

                    // LOG USER IN
                }
            }
        }
    }
}
1

There are 1 best solutions below

4
On BEST ANSWER

You can use ternary operator for the same as

function check_id_switch($id){
    return $HW = ($id == 1) ? 'Hello, World!' : 'Goodbye, World!';
}

Or you can simply use Rizier's answer which he commented as

function check_id_switch($id = '2'){
    $arr = [1 => "Hello, World!", 2 => "Goodbye, World!"];
    return $arr[$id];
}