samedi 2 janvier 2016

How to consolidate various IF conditions into a final result (PHP)?

I am building a script that will process a URL, and will modify it according to various conditions.

I'm not sure what is the best practice to do this; for example, right now, under "Partner A" section, if the category is different than "premiuim", my final_url variable will remain empty. I guess I can make a condition that will check if it's empty and in that case it should apply to it the value of $url3, but it doesn't feel smart enough:

<?php

$url = "http://www.default.com"; // default URL

$url = "something"; // this part will come from a database

$id="something"; // some value to insert later into URL

// the following rules will be followed according to various parameters not defined in this sample code

if($partner == "A") { // Partner A rule:

    $url2 = str_replace('777', '999', $url); // Inital Change

    $url3 = str_replace('?location', '?id=' . $id . '&location', $url2); // Add id, anytime ?location shows up

    if($category == "premium") { // premium category rules:

        $re = "/(?<=TID%3D)\\d+/";  // String to Replace in URL (digits)
        $newtid = "4000"; // Default New TID

                if($special == "yes") { $newtid = "8000";} // special TID value

        $final_url = preg_replace($re, $newtid, $url3); // replace the TID

    }

};


if($partner == "B") { // Partner B rule:

$final_url = str_replace('status=1', 'config=' . $id . '&status=1', $url); //Add id, anytime status=1 exists in url
};

?>  

<p>Final URL: <?php echo $final_url; ?></p>

Also, I'm not sure that the whole structure is the optimal one, in general.

Aucun commentaire:

Enregistrer un commentaire