shopeeon
shopeeon

Reputation: 151

How to execute common code with multiple condition

I am trying to give two or more condition and condition-wise I am try to store a different different values with same variable name and by using that variable I should perform remaining operation (this source code is common for each condition).

Means from two or more condition only one condition is true at a time then store values in variable(Variable values may different but the variable name is same).

Then I execute remaining code by using this variable value.

For example see below code to understand what actually I want.

<?php
$url=$_SERVER['REQUEST_URI'];
$a="http://www.abcd.com";
$b="http://www.abcd.com?pm";
$c="http://www.abcd.com?cm";

if($url==$a)
{
    $deeplink=1234;
    $mer="hello";
}
if($url==$b)
{
    $deeplink=9090;
    $mer="hru";
}
if($url==$c)
{
    $deeplink="xyz";
    $mer="hru";
}
Remaining code by using $deeplink and $mer variables
(this remainig code is common for all condition but it will take 
$deeplink and $mer value at a time and execute this code)
?>

Upvotes: 2

Views: 160

Answers (3)

deval oza
deval oza

Reputation: 79

You can also go for elseif statement.

Like so:

if($url==$a)
{
    $deeplink=1234;
    $mer="hello";
}
elseif($url==$b)
{
    $deeplink=9090;
    $mer="hru";
}
elseif($url==$c)
{
    $deeplink="xyz";
    $mer="hru";
}

Remaining code by using $deeplink and $mer variables (this remaining code is common for all condition but it will take $deeplink and $mer value at a time and execute this code).

PHP elseif statement manual

Upvotes: 0

Armen
Armen

Reputation: 4202

Look here for documentation about php switch - http://php.net/manual/en/control-structures.switch.php

In two words in switch $url is compared with each case value like $url == "http://www.abcd.com" and triggering case block content till break;

switch ($url) {
    case "http://www.abcd.com":
        $deeplink=1234;
        $mer="hello";
    break;
    case "http://www.abcd.com":
        $deeplink=9090;
        $mer="hru";
    break;
    /*... other conditions if you need more */
    default: // <- if no match found your switch will come to default case
        $deeplink=false;
        $mer="";
}

Upvotes: 1

Muhammet
Muhammet

Reputation: 3308

You can and should use switch statement when you want to compare one variable (or expression) with many different values.

<?php
$url=$_SERVER['REQUEST_URI'];
$a="http://www.abcd.com";
$b="http://www.abcd.com?pm";
$c="http://www.abcd.com?cm";

switch($url){
  case $a:
    $deeplink=1234;
    $mer="hello";
    break;
  case $b:
    $deeplink=9090;
    $mer="hru";
    break;
  case $c:
    $deeplink="xyz";
    $mer="hru";
    break;       
}

Remaining code by using $deeplink and $mer variables
(this remainig code is common for all condition but it will take 
$deeplink and $mer value at a time and execute this code)
?>

Upvotes: 1

Related Questions