AAA
AAA

Reputation: 3168

How to do 2 equal statements upon certain conditions?

I need to use different modules based on what value the $what variable holds. There are 2 variables; me and others. If $what = me i want them to see me.php an if $what = others i want them to see others.php. I don't know how to update the snippet that will also take $what = other scenario under consideration.

How to do that?

  $what = "me";

  if ( $q === $what ) {
require("me.php");
  } else {
  require("all.php");
  }

Upvotes: 1

Views: 60

Answers (6)

bigblind
bigblind

Reputation: 12867

there are multiple ways to do that, the simplest being

if ($what=="me")
    require('me.php');
else
    require('all.php');

or, in case other values might be added in the future, you could do a switch statement

switch ($what) {
    case 'me':
        require('me.php');
        break;
    case 'others':
        require('all.php');
        break;
    default:
        require('all.php');
        break;
}

In the above case, I assume that showing the all page by default if something goes wrong is the most secure, unless you have something like error.php

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816312

You need else if.


That said, an improvement in terms of extensibility would be to use an array as map:

$pages = array(
    'me' => 'me.php',
    'others' => 'others.php'
);

$page = 'all.php';

if(isset($pages[$q])) {
    $page = $pages[$q];
}

require($page);

Upvotes: 2

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

You need elseif statement.

 $what = "me";

 if ( $q === $what ) {
    require("me.php");
 } elseif ($what === "others") {
    require("all.php");
 } else {  // optional "catch all condition"
   die("Should not be here");
 }

Upvotes: 2

Jason Small
Jason Small

Reputation: 1054

$what = "me";

if($what == 'me' ){
     require("me.php");
}
elseif($what == 'others'{
     require('others.php')
}
else{
    // There was no variable
}

Upvotes: 1

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

You could use else if.

if ($a == "a") {
   // Do something
}
elseif ($a == "b") {
   // Do something else
}
else {
    // Do something
}

You should use an switch here.

switch($a) {
   case "a":
       // Do something
       break;
   case "b":
       // Do something
       break;
   default:
       // Do Something
       break;
}

Upvotes: 0

n00dle
n00dle

Reputation: 6043

Do you mean something like this?

if ( $q === "me") {
    require("me.php");
} elseif ( $q === "others" ) {
    require( "others.php" );
} else {
    require("all.php");
}

Upvotes: 0

Related Questions